logo codesdope

Functions in Python

We have already used functions like len(), split() 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.

def is_even(x):
	if x%2 == 0:
		print "even"
		print "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.
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:

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"
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 that function.
Let's write the code to calculate and print the sum of two numbers.

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

Let's see one more example

def checkdiv(x,y):
	if x>=y:
		if x%y == 0:
			print x,"is divisible by",y
			print x,"is not divisible by",y
		print "Enter first number greater than or equal to second number"
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

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:
		i = i-1
	print c
[43, 6, 2, 5, 3, 6, 4, 2]


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

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

Here, our function is returning us a Boolean (True or False). Let's see one more 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:
		i = i-1
	return c
z = rev([2,4,6,3,5,2,6,43])
print z
[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:

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

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 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'.

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
		return x*factorial(x-1)

print factorial(0)
print factorial(1)
print factorial(4)
print factorial(5)
print factorial(10)

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'
    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:
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)
So, it will return 6.

For 4

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. Eg- 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
prev = {0:0,1:1}
def fib(n):
	if prev.has_key(n):
		return prev[n]
		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)

has_key has been removed in Python 3. You can use in operator instead i.e.,
if n in prev.keys().

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

Download Our App.
BlogsDope App
Get it on Google Play
Doubt? Ask question

Welcome.please sign up.


Welcome.please login.