Search

A Guide To Python Functions

When we write code we often have groups of related statements clustered together. It would be bad practice to continue repeating those statements. Good programmers group them together in a function. So, we will define our function as a group of related statements that perform a specific task.

python functions

 

Before we delve right into showing how functions are written in python, let’s explore the advantages of using functions in python.

Advantages of using python functions

Using functions rather than just clumping our code statements from line to line has several advantages. I will highlight three:

1.They make for code reuse – reusability.

Take for example we want to multiply a sequence of numbers 5,3, 4 etc. Writing code this way is foolhardy:

    
x = 5
y = 3
z = x * y
m = 4
n = z * m

It stresses the programmer’s resources. With a python function, we could do the multiplication any number of times with any number of objects. Like this:

    
def mult(x,y):
    return x * y

z = mult(5,3)
n = mult(z, 4)    

Code reuse becomes very important when we are dealing with a program that contains several lines of code. It would help for readability and understandability using a function.

2. They make the program manageable - modularity

Taking the example above. You could see that by breaking the statements into smaller chunks, we can manage the code. We could prevent the code from running off into several lines that would make a reader lost about the direction of the code.

When you have several functions working together, they exemplify the concept of decomposition in computer science. For example, for a laptop to function there are different parts. Take the screen, the keyboard, the charger, and the mouse as different parts exemplifying the functions of the laptop. When they work seamlessly, they achieve the idea of decomposition that makes functions a great idea for good programming practice.

3. It helps avoid errors in the code.

Using functions in coding can prevent errors, especially when you have several names that have to be defined. Python functions define their own namespace so that variables do not conflict with one another.

Now, how do you define a python function.

Python function definition.

The syntax for a python function is:

    
def function_name(parameters):
    ‘‘‘docstring’’’
    statement(s)
    return statement

The first line from the syntax above is called the function signature. The signature starts with the keyword ‘def’. The keyword ‘def’ tells the python interpreter that this is a function. Then next is the function name. The function name is unique to the function. You cannot start the function name with a number. It follows the rule of python as for writing identifiers. Then following it are the parameters of the function enclosed in parenthesis. Function parameters are the arguments the function accepts. We have discussed function parameters and arguments in another post. Following the function signature is the block of code that defines the body of the function. A colon ‘:’ is used to separate the signature from the body of the function.

The body of the function consists of docstrings which represent the documentation of the function followed by the statements that the function has to execute. Note that the documentation or docstrings are optional but it is good programming practice to include them in your functions. The documentation is enclosed by three quotation marks. Then the statements to be executed comes after the documentation. The last statement in your function should be an optional return statement. This ends execution of the function. Note that the return statement can occur anywhere in the body of the function but is usually found at the end and when they occur the function stops execution and control transfers to the caller of the function.

The function’s docstrings are a great idea for abstraction. That means, using the docstrings alone, you do not need to know how a function works to use it. The documentation or docstrings tells you what it does and it guarantees you that it works as the author states it.

When a function does not have a return statement, then that function returns None.

Let’s look at a typical function that includes all the syntax for a function. The docstrings or documentation in the function below explains what the function does.

    
def count(data, target):
    ''' Counts the number of occurrences of target
    value within data, an iterable
    Returns the number of occurrences as an int '''
    n = 0
    for item in data:
        if item == target: # found a match
            n += 1
    return n

The code above illustrates the typical features that can be found in a function.

Let’s look at another example that shows that a return statement can be placed anywhere in the body of a function but when it is encountered, it automatically returns control to the caller of the function.

In this contrived example, you can see that if the user enters Michael, the function ends at the return statement on line 7 but if some other name is entered, the return statement at line 9 ends the function and returns control to the caller of the function which is the print statement on line 12.

Now we have been talking about the caller of a function. Let’s us define how to call a function.

How to call a function.

The three ways you can call a function is either from the python prompt, from another function, or from within the program. To call a function, you write the name of the function followed by the parameters that you are passing to the function.

I will show examples where you can call a function from another function and within the program. They also apply to the python prompt.

a. From within the program.

In the function, mult, above we called the function on line 4 when the name of the function was used and then the parameters we want to pass to it were included in parentheses. Note that the parameters must correspond to the arguments of the function in the function signature. For a refresher on function arguments, you can see this post on positional and keyword arguments in python functions.

b. From within another function.

Functions are first-class citizens in python so you can call them from within another function. They can also be parameters to another function.

Take this example of a function calling other functions. Run it to see how it works.

The third function calls on the first and second functions to print their statements.

Also, see how the enter_name function below uses another function, print_name, as its argument or parameter, and then in its body it calls the function that was passed as an argument. The f formal argument is bound to the print_name actual argument that was passed when the enter_name function was called.

The function, enter_name, accepts another function as argument which was passed to it on line 8. It then calls the function in its body and that function when called prints out its statement.

These shows that functions are first class citizens and you can call them from even another function, and not only from within the program.

Variable scope and lifetime in functions.

The scope of a variable can be defined as the portion of a program where the variable is recognized. When a function is entered, the python interpreter creates a new scope or environment which contains the variables that the function recognizes. When a scope is created, names are being mapped to their values. Some of the variables that are scoped on function call are the parameters that are passed to the function. When the function is defined the parameters are called its formal parameters and when the function is called, the parameters are called actual parameters. When the function is called, a new scope is produced where the formal parameters are bound to the values of the actual parameters within the function namespace.

Also, other variables that are scoped in the function are any variables that are declared inside the function.

Take the following code for example:

    
def mult(x,y):
    ''' Returns the multiplication
    of its arguments, x and y, 
    where x and y are ints '''
    z = x * y
    return z

n = mult(2,3)    

When the function, mult, is called at the last line, python creates a new environment or scope for the variables that are recognized within the python function. First, it recognizes the formal parameters, x and y. It then binds x to its corresponding actual parameter, 2, and binds y to its corresponding actual parameter, 3. It then recognizes z that is declared within the python function. It multiplies the numbers and binds z to the value of the multiplication. So, we have 3 variables scoped within the function: x, y and z namely.

The variable n is outside the scope of the function and is said to be in a global scope.

Note that all the variables that are scoped in a function exists as long as the function is running. When the function stops running or returns, python garbage collects all the variables scoped within that function.

To see how this garbage collection of variables is done, let’s take an example.

You can see that the x in the function scope is now 30 when you run it, but the x variable in the global scope is still unchanged at 5. This is because when the function was exited the x in the function scope was destroyed and ceased to exist except for the x variable in the global scope. That shows you that the lifetime of variables in a function’s scope are for as long as the function is still running. Take note of that although there is an exception - functions defined as python generators which yield values. The following blog post explains python generator functions where the variables within its scope are not garbage collected.

One other point I want you to note about scopes is that even if a variable is not scoped within a function, that variable can still be accessed from inside the function but it cannot be modified from within the function.

Example: Global variables, x and y, accessed from within the function, mult.

Next example: We would have an UnboundLocalError if I try to modify either x or y without scoping them to mult.

I hope you now have all it takes to start writing your own functions in python and experiment with its powerful capabilities.

Happy pythoning.

Matched content