Topics

Define Functions in Python

Welcome to a tutorial on Writing User-defined Functions in Python. 

In the previous tutorial, you were introduced to functions, how functions are used, and the several inbuilt functions. 

Hence, since functions are built, if we want to use them, all we need to was simply call them and provide the necessary arguments. 

Functions defined explicitly (or by a user) in a program, help to divide the whole program into sub-parts, thus making it more readable, easy to revise the code, and to fix any errors (or bugs).

Let's learn about user-defined functions (creating our functions) in Python. Just as learned in previous tutorials, in other to use a built-in function, there is a need to import the module by which the function is defined in our program. Check out the example below, where we imported the math module to use the floor() in-built function.

import math

a = 2.3
print ("The floor of 2.3 is : "+ math.floor(a))

When we open the module file ( a file in Python), we can see the definitions of various functions. You will get to do this on your own before the end of this tutorial, by defining your user-defined functions.

 

Structure of function definition

Below is the general syntax to create a function.

def functionName(parameter1, parameter2, ...):
    logic/algorithm statements
    ...
    return someData

The important part here is the indentation, the definition of the function should be indented by a tabspace after the def functionName(parameter1, parameter2) in the syntax.

In the syntax above, the first line is called function header and starts with the keyword def which means defines, because it is the starting point when defining a function. The next step is the function’s name, where a function is given a name such as multiply, add, or anything that identifies the task of the function.

Afterward, the parameter comes inside the circular braces. These parameters are the required values the user inputs and are used inside the function during the operation. 

In one of our previous tutorials, we put several numbers while calling math's function such as sin(3.14), where the 3.14 is the parameter value, and we know that without the value, the sin() function will not have a value to perform the sine operation. Back to base, you can specify your user-defined function to expect some parameters for successful execution, while defining the function in your program. 

Now, in the second line, there are the logic/algorithm statements, where we will be utilizing all the parameters (if any) to obtain the purpose of the function. There are also, various operations loops, conditional statements, and so on, to perform it. Let’s use the add() function as an example, if we perform a simple addition of –a +b and the result is stored in a variable, like c, thus inside the add() function, there is an expression: c=a+b, and a and be are the input values. 

Then lastly, the return statement comes. The first thing to know is the return statement as it is not compulsory to have it a function. However, if your function is required to return a value after any operation, then you must use the return statement to output that value, otherwise, your function does not need it. Therefore, we must know when to use the return statement. As such the returned data can be anything like a string, a Boolean value, a number, or anything you can think of.

Now, if we want to return any value, all that is needed is to mention the value which we want to return, next to the return keyword. Check out the example below.

def add(a, b):
    c = (a+b)
    return c

Alternatively, (a+b) can be returned directly, without storing it to some other variable.

def add(a, b):
    return (a+b)

Once a function is defined, it can be used to simply call it just as it is for the built-in function. Check out the example below.

>>> print add(5, 9)

Output:

14

In addition, we can as well pass a function as a parameter.

>>> print add(5, add(7, 6))

Output:

18

You might be confused, let me clarify what happened above, firstly the add(7,6) is evaluated and returns 13; this result (13) is passed inside the second add() function as a parameter that will be added with 5. Thus, our final result will be the output of add(5,13) which is 18.

 

Return Type of a function

In Python, every function has a return type, which is the type of values it returns, and it is easy to ascertain the return type of a function. For instance, in add() function, if a and b are integer, then the add() function will return an integer value and will be its return return-type. Also, if the function is returning a list, its return type will be a list. where for a built-in function, you can as well find the return type of every function that is specified in the official documentation.

Recall that we stated above, that it is optional for functions to have a return type. Now, what will be the return type of a function that does not return anything? The answer to this is void, this is quite similar to empty or nothing, meaning that there is no return statement. As such the return type is void.

Now, we will learn how to use the functions with a return-type void.

Note: since this return type does not return anything, it can be used to break our program into smaller units or bits.

Check out the example below of a simple program, in which a positive number was taken as input from the user and printed all the even numbers, and doubled all the odd numbers that start from 1 to the number

n = input()
for i in xrange(1, n+1):
	if i%2 == 0:
		print i
	else:
		print 2*i

Let's attempt to obtain the above with a function, as we will start by defining the function on the top. However, it doesn't matter where you define the function, since it does not affect the flow of execution of the function. Although, it's a good practice to define all the functions at the start of your program since that is where all the programmers look for all the user-defined functions when they are reviewing any code in a program.

def check(k):
	if (k%2==0):
		print k
	else:
		print 2*k

n = input()
for i in xrange(1, i+1):
	check(i)

From the above example, we picked up the logic of checking whether the number is even or not and defined it inside the check() function. As such we can call it in the for loop, and then pass a new value to it in every iteration. Interestingly, it cleaned up the for a loop a bit and made it look tidier or cleaner.

The example above is a simple program, but some programs might have 100s of lines of code, so dividing such a program into functions is the best thing to do.

In addition, one advantage of using a function is that you can re-use that function at any time, just by calling it. From the above example, if we want to print a number if it's even or prints the double of it if it is odd, so all we need to do is simply call the function, and then pass that number as the argument, and it is done, just like the check(9).

 

Default Arguments

In Python, the Default arguments are used when you need to pre-set the value for the parameters. That is, if in the future we don't pass any variable as an argument while calling the function, the function will assume the default value and execute its statements.

Check out the example below on how to define the default arguments.

>>> print add()

 

Python will throw an error if a function has no default parameter. Now, we will set the default arguments for the add() function, for it to work without argument values. So will take the default value to be 0, so the returned value will be 0+0=0, which is reasonable, as we have passed any parameter/argument value.

So the updated add() function will be:

def add(a=0, b=0):
    return (a+b)
>>> print add(10, 6)
>>> print add()

Output:

16
0

 

Aliasing function names

Python program has a special feature in which we can create an alias of any function, that is, if a function name is too long and not worth typing every time, a new name can be assigned to it, without altering the original function. Let’s consider the add() function example, if we want a shorter or different name for this function, but without editing the original function, the function aliasing feature can be used. Check out the below where we can rename ad() to a():

>>> a = add

That is it! So after that line, the ad() and a() would call the same function, hence, the parameters will have to be the same as well. Check out the example below to see how this will work.

>>> print a(9, 8)

Output:

17