Post

Python Functions - Creating Our Own Functions For Reusable Code...

Earlier in this series, I learned about built-in functions, which are pre-built and used throughout Python code. When creating code, we need to be able to define our own functions.

Python Functions - Creating Our Own Functions For Reusable Code...

Building functions in Python enables us to use repeated code without repeating code. You can build a function once and have it used throughout your code several times.

Developers build functions to create a process that transforms the data for an objective focussed output. An output we can use to perform other functions or be a part of our code.

Creating a Function

Creating a function is similar to creating a variable. The only contrast here is that we must use the term def before the function name, thereby telling Python we intend to create a function.

1
2
3
4
5
6
def function_name(): # Create a function
    # Coding goes here

# To invoke/call the function later:

function_name()

Tip: We should try and keep to using the snake case naming convention we learnt before.

Parameters in Functions

Parameters are the input values we pass into our functions. These values are then used within the function to go through a process of change and produce information as the output.

A better explanation of this would be to think of parameters as being raw bits of data. Your function would then be the transformation of that data, and the output would be information which readable or usable.

With this manner of thinking, we are able to achieve efficient code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#1)
def greeting(): # Without parameters
    print("Hello There")

greeting() # Hello There

#2)
def greeting(name): # With parameters
    print(f"Hello There, {name}!")

greeting("Sheikh") # Hello There, Sheikh!

#3)
def greeting(name): # Using a variable as a parameter
    print(f"Hello There, {name}!")

var_a = "Sheikh"
greeting(var_a) # Hello There, Sheikh!

The examples I have provided illustrate the use of parameters within functions.

Using Multiple Parameters

This concept can be broken down into two main ideas: using multiple points of input for different data types, or using the same data type across multiple inputs.

The benefits we gain from using this allow us to create complex code structures within our functions.

An example of this could be that we take different data types as inputs, then change them to other data types. We can also have them merge into one string data type, etc.

The idea I would like to get across is that multiple parameters are common within functions, and that’s solely down to what we can do with functions.

1
2
3
4
5
6
def greeting(fname, sname, age):
    print(f"Hi, I'm {fname} {sname}, and I am {age}.")

greeting("Sheikh", "Hussain", 29)

# Hi, I'm Sheikh Hussain, and I am 29.

A more practical example would be:

1
2
3
4
5
6
def greeting(num1, num2):
    total = num1 + num2
    print(total)

greeting(1, 2)
# 3

Note: When creating a function, we define the parameters it will use, for example def function_name(param1, param2). When we call on the function, we place arguments it will use, such as function_name(arg1, arg2).

The other method of using multiple parameters and arguments would be to have them assigned recursively. Recursive assignment of arguments or parameters use the * symbol when it is being declared. For example, def function_name(*param) is how would would assign multiple arguments to one parameter.

Then, when it comes to using that function, you can specify all the different inputs for it, function_name(arg1, arg2, arg3) and each of those inputs would go through the same process in the function. This is very similar to how the unpacking function on lists and strings work.

1
2
3
4
5
def function_name(*para):
    code

function_name("arg1", "arg2", "arg3", 4, 5.5, True)
# This is an example to show that different data can be used.

A more realistic example would be:

1
2
3
4
5
def generate_groups(team, *args):
    print(team)
    for i in args:
        print(i)
print(generate_groups('Team-1','Asabeneh','Brook','David','Eyob'))

Keyword Arguments

By now, we should be aware of what key, value pairs are from dictionaries. We can use the same analogy when it comes to using parameters and arguments in functions.

1
2
3
4
5
def function_name(par1, par2):
    code

print(function_name(par1 = "Sheikh", par2 = 5))

1
2
def function_name(para1 = "Sheikh", para2 = 5):
    code

This is just a method used to assign either a default value or a set value to a parameter for your function.

Using default parameters

Default parameters are what the function uses as a pre-defined parameters when no arguments are provided. It’s similar to using placeholders, except these do have data that you use. Later, throughout your code, at specific points, you insert the new data as arguments for each parameter.

1
2
3
4
def function_name(para1 = "", para2 = 5):
    code

function_name("New Arg", 10)

Returning a Value

I wanted to ensure I included this at the beginning of this topic, as I found it to be quite relevant later on. So far, I have demonstrated that we can return a result using the print() function.

This would be the natural approach to having values outputted to us; however, the correct method to use is return.

When I had discovered this, my coding logic made a little more sense, and I even started to code a little better.

The problem is, we will all develop different habits when it comes to coding and mine us overly using the print() function.

1
2
3
4
def greeting(name,age):
    return f"Hey, I'm {name} and I'm {age}"

print(greeting("Sheikh", 29))

Tip: The reason why the information is being printed like normal in this example is because we are using f-string notation to tell python to convert all the parameters in to a string format for print.

We still need the output to be printed onto the terminal; therefore, we enclose our function inside a print() function when using return; however, because we have used the return feature, we can now have another function recognise the output of this function as data and use it as input.

When using the return function, we bring back the value as opposed to just having it printed. Returning a value enables other functions to use it.

Another perspective could be to look at how we use variables. We use variables to store data; functions can be thought of in the same light.

The key difference is that a function performs a process first, and only then returns the resulting value so it can be stored or reused elsewhere.

Note: returning values don’t have to be in string format only, we can have it return other data types like boolean and also perform functions.

Using a Function As an Argument

Python allows us to use a function as a parameter of another function. For this work, you would use the return function I mentioned earlier. This just enables the output of one function to be the input of another,

This concept is often referred to as higher-order functions and is usually used in callbacks, decorators, and functional programming patterns.

1
2
3
4
5
6
7
8
9
def say_hello(name):
    return f"Hello, {name}"

def run_function(func, value):
    return func(value)

print(run_function(say_hello, "Sheikh"))

#Hello, Sheikh

Key Takeaways

The main concept I have taken from this module is the ability to pass a function as an argument to another function. Although my coding experience is still developing, learning this has shown me how flexible functions can be and how they allow for a wide range of possible outputs. It has helped me better understand the creative potential behind writing functions.

Another important takeaway is the ability to handle multiple inputs using a single argument. By using the asterisk * operator, we can accept several values without needing to define each one individually. This approach helps reduce repetition in code and makes functions more efficient and easier to manage.

This post is licensed under CC BY 4.0 by the author.