Close
Close

Python Functions


We have already used functions provided by Python like len(), split(), etc. Do you know we can also create our own functions? Yes, we can create functions for performing different tasks. In this chapter, we will learn to make our own functions.

Why do we need functions?


Function is a set of statements written together and given a name. We can call that set of statements at any place in our program by just calling its name and without writing the whole set of statements again. Quite convenient, right?

function in Python

Suppose we need to check where a number is even or not multiple times in our program. Instead of writing the same login again and again, we can write a function and call it whenever we need to check whether a number is even or not.

Let's take an example.

# function definition
def display(x):
    print("Hello")
    print("You passed:", x)

# calling function
display(10)
Output
Hello
You passed: 10

def is a keyword used for making functions. To make a function, we first write def and then the name of the function.

In the above example, display is the name of the function.

If we want to pass some value to a function, we give a parameter in the function definition. In our example, 10 is the value passed to the function and x is the name of the parameter. So, whenever a value is passed to the function, the parameter takes that value. Therefore, x takes the value 10 in our example.

parameter and argument of function in Python

The body of the function consists of the statements print("Hello") and print("You passed:", x).

So this was the description of the function. Now let’s call this function. A function is called by writing the name of the function and passing a value (if required) to it. In the above example the function is called by writing display(10).

Once a function is called, the statements in the body of the function are executed. So, when display(10) was called, then the statements inside the function display got executed with x = 10.

Notice that the body of the function is also represented by equal indentation (margin) from the left.

Let’s take another example.

# function
def is_even(x):
    if x%2 == 0:
        print("even")
    else:
        print("odd")
 
is_even(2)  # calling function
is_even(3)  # calling function
Output
even
odd

In this example, is_even is the name of a function. From the body, you must have understood what the function does. It prints "even" if the value passed to it is divisible by 2, otherwise it prints "odd".

When the function is called for the first time, 2 is passed in the function call. So, the statements in the body of the function are executed with x = 2.

Similarly, 3 is passed in the second function call. In that case, the statements in the body of the function are executed with x = 3.

It is not compulsory for a function to have a parameter. We can also define functions without any parameter. Let's see this example:

# function
def print_poem():
    print("I am playing with computer")
    print("Soon I will be master")
    print("You will play my written game")
    print("I will get a huge fame")
 
print_poem()  # calling function
Output
I am playing with computer
Soon I will be master
You will play my written game
I will get a huge fame

As we saw here, we have not passed any parameter. Whenever we want to print the whole poem, we just have to call the function print_poem().

Let's write a program to calculate and print the sum of two numbers.

def sum():
    a = int(input("Enter first number >>>"))
    b = int(input("Enter second number >>>"))
    print(a+b)

sum()
Output
Enter first number >>>2
Enter second number >>>5
7

Python Parameters and Arguments


Parameters and arguments are just the different terms used for the variables/values you are already aware of. Parameters are the variables we use in the function definition whereas arguments are the values we pass in the function call.

parameter and argument in Python

Let’s again look at the first example of this chapter.

# function definition
def display(x):
    print("Hello")
    print("You passed:", x)

# calling function
display(10)
Output
Hello
You passed: 10

In this example, the variable x is called the parameter and the value 10 is called the argument.

Look at another example in which the function has more than one parameter.

def checkdiv(x,y):
    if x>=y:
        if x%y == 0:
            print(x,"is divisible by",y)
        else:
            print(x,"is not divisible by",y)
    else:
        print("Enter first number greater than or equal to second number")

checkdiv(4,2)
checkdiv(4,3)
checkdiv(2,4)
Output
4 is divisible by 2
4 is not divisible by 3
Enter first number greater than or equal to second number

While calling the function checkdiv(), the first argument is matched with the parameter x and the second argument is matched with the parameter y. The rest of the code is simple. The function checkdiv() checks if the first number x is greater than or equal to the second number y. If the first number is greater or equal, it simply checks whether the first number x is divisible by the second number y or not. Whereas, if the first number is smaller than the second number, then the interpreter prints("Enter first number greater than or equal to second number").

Our own reverse function

We already have the reverse() function provided by Python to reverse the elements of a list. Let's create our own reverse function.

def rev(a):
    c = []
    i = len(a) - 1 #len(a)-1 as index will go to 1 less than length as it starts from 0.
    while i >= 0:
        c.append(a[i])
        i = i - 1
    print(c)

rev([2, 4, 6, 3, 5, 2, 6, 43])
Output
[43, 6, 2, 5, 3, 6, 4, 2]

That was fun!

Python Return


Functions can do one more thing, they can return us something. It means that a function can give us something back. Whenever a return statement is executed in a function, it terminates the function and returns some value to the place from where the function was called

You will understand this from some examples.

def is_even(x):
    if x%2 == 0:
        return True
    else:
        return False

print(is_even(1))
print(is_even(2))
Output
False
True

Here, our function is returning us a Boolean (True or False). Inside the function is_even(), if x%2 == 0 is True, then the function returns True, otherwise it returns False.

Look at another example.

def rev(a):
    c = []
    i = len(a) - 1 #len(a)-1 as index will go to 1 less than length as it starts from 0.
    while i >= 0:
        c.append(a[i])
        i = i - 1
    return c
 
new_list = rev([2, 4, 6, 3, 5, 2, 6, 43])
print(new_list)
Output
[43, 6, 2, 5, 3, 6, 4, 2]

Returning Multiple Values from a Python Function


We can also return multiple values from a function.

def calculation(num1, num2):
    result1 = num1 + num2
    result2 = num1 * num2
    return result1, result2

sum, product = calculation(10, 20)
print("Sum:", sum, "Product:", product)
Output
Sum: 30 Product: 200

The function calculation() returns two values. The first returned value result1 is assigned to sum and the second returned value result2 is assigned to product.

The function in the above program can be rewritten in a lesser number of lines as shown below.

def calculation(num1, num2):
    return (num1 + num2), (num1 * num2)

sum, product = calculation(10, 20)
print("Sum:", sum, "Product:", product)
Output
Sum: 30 Product: 200

Calling a function inside another function


Yes, we can call a function inside another function.

Let's take an example of checking a number's divisibility by 6. For a number to be divisible by 6, it must be divisible by both 2 and 3. In the following example, we have a function is_even() to check if it is divisibility by 2. The div6() function calls is_even() inside itself to check the number's divisibility by both 2 and 3. Let's see how:

def is_even(x):
    if x%2 == 0:
        return True
    else:
        return False
# div6 function to check divisibility by 6
def div6(y):
    if is_even(y) and y%3 == 0:
        return True
    else:
        return False
		
print(div6(12))  # calling div6 function
Output
True

We have called the is_even() function inside the div6() function.

Here, is_even() will return True if the given number is even or divisible by 2. The condition is_even(y) and y%3 == 0 will be True only if is_even() and y%3==0 both are True, which means that the condition will be True if the number is divisible by both 2 and 3 or divisible by 6.

If a variable is defined inside a function, then it is available only to that function and not outside the function.

Python Recursion


Recursion is calling a function inside the same function. Before going into this, let's learn some mathematics.

We will calculate the factorial of a number. Factorial of any number n is (n)*(n-1)*(n-2)*....*1 and written as (n!) and read as 'n factorial'. For example, 4! = 4*3*2*1 = 24

3! = 3*2*1 = 6
2! = 2*1 = 2
1! = 1
Also, 0! = 1

Let's code to calculate the factorial of a number:

def factorial(x):
    if x==0 or x==1:
        return 1
    else:
        return x*factorial(x-1)

print(factorial(0))
print(factorial(1))
print(factorial(4))
print(factorial(5))
print(factorial(10))
Output
1
1
24
120
3628800

Let's go through this code.

If we give 0 or 1, our function will return 1 because the values of both 0! and 1! are 1. It is very simple up till here. Now see what happens if we pass 2 to our function factorial().

else:
    return x*factorial(x-1)

factorial(x-1) → When x is 2, factorial(x-1) is factorial(1) and it will be equal to 1. (This is called recursion, the factorial() function is called inside itself). So, the result is 2*factorial(1) = 2*1 i.e. 2.

Therefore, the function will finally return 2.

 

Now let's see for 3:

x*factorial(x-1)
3*factorial(2)    Now factorial(2) will be called and then it will be 2*factorial(1):
3*2*factorial(1)    As factorial(2) will be 2*factorial(2-1)
3*2*1
So, it will return 6.

For 4

4*factorial(3)
4*3*factorial(2)
4*3*2*factorial(1)
4*3*2*1

If you have understood this, you have just done a thing which most of the programmers find difficult in their beginning days.

factorial function in Python

Do you know about the Fibonacci series?


It is a series having its 0th and 1st terms 0 and 1 respectively.

Examples of series:

2, 4, 6, 8, 10, ... is a series. Its nth term is n*2. For example, 1st term is 2*1 = 2, 2nd term is 2*2 = 4.
One more example can be 11,15,19,23,... . Its 1st term is 11 and any other nth term is (n-1)th term + 4. Eg- 2nd term is 1st term + 4 = 11+4 = 15. 3rd term is 2nd term + 4 = 15+4 = 19.

The 0th term of the fibonacci series is 0, the 1st term of the fibonacci series is 1, and its nth term f(n) = f(n-1)+f(n-2).

This means that

f(2) = f(1)+f(0)
= 1+0 = 1

f(3) = f(2)+f(1)
= 1 + 1 = 2

Now, let's program it.

prev = {0:0,1:1}
def fib(n):
    if n in prev.keys():
        return prev[n]
    else:
        fi = fib(n-1) + fib (n-2)
        prev[n] = fi
        return fi
		
print(fib(0))
print(fib(1))
print(fib(2))
print(fib(3))
print(fib(4))
print(fib(5))
Output
0
1
1
2
3
5


prev = {0:0,1:1} → We are using a dictionary to store the fibonacci series corresponding to the nth term. Initially there are only two numbers f(0) = 0 and f(1) = 1.

Coming to the next line:

if prev.has_key(n) → If the required term is in the dictionary then it will simply return that, else, it will calculate and also store the corresponding calculated value in the dictionary.

For f(2):

fi = fib(n-1) + fib(n-2) => fi = f(1)+f(0) = 1.

prev[n] = fi It will update our dictionary. And in the last line 1 is returned.

For f(3)

fi = f(1)+f(2)

For f(1), simply 1 will be returned and f(2) will be calculated as above and 1+0 i.e., 1 will be returned.

Similarly f(4) will be calculated.

 

So now you know that we can create our own functions to perform any task like checking if a number is even or odd, returning the factorial of a number or anything else you can think of. It’s also important that you practice from the practice section to have a hold over this topic.

To learn from simple videos, you can always look at our Python video course on CodesDope Pro. It has over 500 practice questions and over 20 projects.
Those who dare to fail miserably can achieve greatly.
- John F. Kennedy


Ask Yours
Post Yours
Doubt? Ask question