logo codesdope

Functions in Python


We have already used functions like len(), split(), etc. but in this section we are going to make our own functions.

Why do we need functions?


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

function in python

Let's take an example.

  • Python 2
  • Python 3
def is_even(x):
	if x%2 == 0:
		print "even"
	else:
		print "odd"
is_even(2)
is_even(3)
def is_even(x):
	if x%2 == 0:
		print("even")
	else:
		print("odd")
is_even(2)
is_even(3)
Output
even
odd

def is a keyword used for making functions. We first write def and then the name of the function to make a function.

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

(x) - We gave a parameter named 'x' to the function in the function definition. Now, while calling the function, we need to give an argument to it. Our passed argument will be x in function. For example, 2 is given in the first function call. In the function, x is 2 (as we have passed 2).

In the same way, during second time, 3 is passed. So, x is 3 there.

Once a function is called, codes inside the function are executed. So, when is_even(2) was called, then the codes inside the function 'is_even' were executed with 'x=2'.

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

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

  • Python 2
  • Python 3
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()
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()
Output
even
odd

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

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

  • Python 2
  • Python 3
def sum():
	a = input("Enter first number >>>")
	b = input("Enter second number >>>")
	print a+b
sum()
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

Let's see one more example

  • Python 2
  • Python 3
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)
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

Here our first parameter will be matched with x and the second will be matched with y. And rest of the code is simple. checkdiv will check the divisibility of the first number by the second number only if the first number is greater than the second number. If this is not the case, then the compiler will print "Enter first number greater than or equal to second number". And if the first number is greater, it will simply check whether the first number(x) is divisible by the second number(y) or not.

Our own reverse function

  • Python 2
  • Python 3
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])
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]

Return


Functions can do one more thing, they can return us something. It means that it can give us something back. It will be clear from some examples.

  • Python 2
  • Python 3
def is_even(x):
	if x%2 == 0:
		return True
	else:
		return False
print is_even(1)
print is_even(2)
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). Let's see one more example.

  • Python 2
  • Python 3
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
z = rev([2,4,6,3,5,2,6,43])
print z
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
z = rev([2,4,6,3,5,2,6,43])
print(z)
Output
[43, 6, 2, 5, 3, 6, 4, 2]

Here, our function is returning a list.

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 with 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 its divisibility with 2. The div6() function calls is_even inside itself to check the number's divisibility with both 2 and 3. Let's see how:

  • Python 2
  • Python 3
def is_even(x):
	if x%2 == 0:
		return True
	else:
		return False
# div6 function to check divisiblity by 6
def div6(y):
	if is_even(y) and y%3 == 0:
		return True
	else:
		return False
def is_even(x):
	if x%2 == 0:
		return True
	else:
		return False
# div6 function to check divisiblity by 6
def div6(y):
	if is_even(y) and y%3 == 0:
		return True
	else:
		return False
Output

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

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

Function to be called inside another function must be defined before the calling the function (function in which it is being called).
If a variable is defined inside a function, then it is available only to that function and not outside the function.

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:

  • Python 2
  • Python 3
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)
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)

Going for factorial(x-1) i.e., factorial(1) and it will be 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.

Do you know 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.

0th term of fibonacci series is 0. 1st term of fibonacci series is 1. And its nth term f(n) = f(n-1)+f(n-2)
It 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

  • Python 2
  • Python 3
prev = {0:0,1:1}
def fib(n):
	if prev.has_key(n):
		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)
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.

You have completed most of the programming parts. In the next section, you will be introduced to the object-oriented features of Python. You need to practice on these concepts before going further.

Winning doesn't come cheaply. You have to pay a big price.
- Jeev Milkha Singh

Doubt? Ask question
Close

Welcome.please sign up.

Close

Welcome.please login.