Python Function : Python Tutorial 16

Python Function tutorial : What is a function ? 

Suppose you need to find the factorial of a number and you wrote a loop to calculate it. Again in the same project, factorial calculation is required again for a different number. In this case, we can write one similar “for” loop as before . But don’t you think that it would be better if we write the “for” loop only for one time and on second case, we will just run it using a “name” ? That will be great, if factorial is required to calculate in thousands of places, we don’t have to duplicate the same code again and again. These types of “ reusable code block that performs a specific task” is known as function. 

Python Function Types :

Two types of functions are available in python. Built-in functions and User-defined functions. Built-in functions are already available functions in python like print() . User-defined functions are defined by a user . In this tutorial , we will check how to create a function .

Defining a function in python :

The syntax of a function is as below :

def function_name( parameters ) :
    “docstring”
    function_expressions
    return [expression]
  • def” keyword is used to define a function.

- “function_name” is the name of the function. “parameters” are one or more than one input values we are passing to the function. These are optional. We can even have a function with no parameters. In this case , it will be empty parentheses. 

- “docstring” is the documentation string for this function. With this string, we define what this function is used for. Documentation string is optional. 

  • After the documentation, we write the main function body. All lines inside the body should have the same indentation level. 

  • Finally, one optional return statement . It may return a expression that will calculate the final value and return to the caller or return None

Example of a function :

def isEven( num ) :
    if num % 2 == 0 :
        return True
    else :
        return False

This function will check if a number is even or not. If even, it will return “True” , and if odd, it will return “False”.

Calling a python function :

After defining a function, we can call this function from a different function or even directly from the python prompt. 

Let’s try to call the above function :

def isEven( num ) :
    if num % 2 == 0 :
        return True
    else :
        return False


print isEven(2)
print isEven(5)

It will print :

True
False

Passing a argument by reference :

In python, an argument is passed by reference . That means , if you change the argument inside the calling function, it will also change the value of that argument inside the caller.

Let’s take a look into the following example :

def changeDictionary( my_dict ):
    my_dict.update({'first' : 10})
    print "change dictionary ", my_dict

def changeDictionaryAgain( my_dict ):
    my_dict = {'first' : 1 , 'second' : 2}
    my_dict.update({'first' : 10})
    print "change dictionary again ",my_dict

temp_dict = {'first' : 1 , 'second' : 2}
temp_dict_2 = {'first' : 1 , 'second' : 2}


changeDictionary( temp_dict )
print "temp dict changed ",temp_dict

changeDictionaryAgain( temp_dict_2 )
print "temp dict 2 changed ",temp_dict_2

It will print the following output :

change dictionary  {'second': 2, 'first': 10}
temp dict changed  {'second': 2, 'first': 10}

change dictionary again  {'second': 2, 'first': 10}
temp dict 2 changed  {'second': 2, 'first': 1}

First “temp_dict” is passed to thechangeDictionary() function. Inside it, we have change the value of these dictionary. But since we are actually passing a reference , it will also change the main “temp_dict” .

In the second case, we are doing the same thing, i.e. passing the reference to the function “changeDictionaryAgain” . But before changing the value of the dictionary “temp_dict_2”, we have changed the reference by “my_dict = {‘first’ : 1 , ‘second’ : 2}” inside “changeDictionaryAgain” function. So “my_dict” inside this function holds a reference to a different dictionary and that’s why after we have updated the values, these are not reflected outside the function.

Scope of function variables :

Variables defined inside a function are not accessible from the outside. After the function execution is completed, these variables are destroyed.These are also known as local variables. 

Similarly, variables defined outside of functions are accessible from anywhere in the program, known as global variables.

answer = 10

def multiply(num1 , num2):
    answer = num1 * num2
    print "answer inside : ",answer
    return answer

multiply(10 , 2)
print "answer outside : ",answer

Output :

answer inside :  20
answer outside :  10

In this example, we have created one new variable “answer” inside function “multiply” and assign it a value 20. But since it is a local variable, it will not change the value of the global variable “answer”.

Python function unordered arguments :

We can call a function with multiple arguments without passing them in order. For this, we need to use the argument names as keyword with the passing value.

def sampleFunction(var1 , var2):
    print "var1 ",var1
    print "var2 ",var2

sampleFunction( 1, 2 )
sampleFunction( var2 = 2, var1 = 1)

Output :

var1  1
var2  2
var1  1
var2  2

Python function with a default value argument :

def sampleFunction( var1 , var2 = 10 ):
    print "var1 ",var1
    print "var2 ",var2

sampleFunction( 1, 2 )
sampleFunction( 20 )

Output :

var1  1
var2  2
var1  20
var2  10

In the above example, it prints the default value of var2 if nothing is passed for var2 .

Variable Length argument function :

If a * is placed before an argument name, it can take multiple arguments .

def sampleFunction( *var_argument ):
    print "argument : "
    for i in var_argument:
        print i

sampleFunction( 1, 2 , 4, 5)

Output :

argument :
1
2
4
5

For the below example, first no. is send as var1 .

def sampleFunction( var1, *var_argument ):
    print "first argument"
    print var1
    print "argument : "
    for i in var_argument:
        print i

sampleFunction(1,2,4,5)

output :

first argument
1
argument :
2
4
5