Functions in python

In earlier posts we used python interpreter and executed lines of code to see the output.Suppose we want to execute a block of code lines, then function comes for rescue.Functions and methods are used interchangeably in other programming language.However, when we look python from object oriented perspective, their is a subtle difference :
In general term function is used to describe a traditional, stateless function that is invoked without the context of a particular class or an instance of that class. However, method is used to describe a member function that is invoked upon a specific object. Here we will discuss python functions.
Syntax of function in python is:
def function_name(arguments) # def is keyword in python and function_name is an identifier
     body of function # Please mind proper indentation
For better understanding we will write a sample program. Suppose we have an list containing numbers. We have to find how many 2's are there in this list.
Open IDLE(GUI tool of python) and create a file count.py and type following code snippet in it and execute, it will display no of 2's in the list.5
input_list = [12,2,34,56,2,4,5,6,78,12,2,3] #Total no of 2's is 3 

# Definition of countNoOf2 function 
def countNoOf2(input_list_formal):
      count= 0
      for var in input_list_formal:
            if var==2:
                 count= count+1;
      return count

# call countNoOf2 function

countOf2Is = countNoOf2(input_list)
print "Number of 2's is %d" % (countOf2Is )
Let's walk through the code : First we created a list input_list of integers. After that we define a function to count number of 2's: as mentioned earlier def is the Keyword which indicate that we are writing a function and countNoOf2  is an function name(it can be any valid name) , input_list  is the formal parameter to the function and with proper indentation we write body of the function.This function returns count to the caller. At the end, we call  this function
countOf2Is = countNoOf2(input_list). Here countOf2Is is place holder to store returned value from function call and input_list is actual parameter.

Note : 1. Python is a dynamically typed language, and therefore a Python signature does not designate the types of those parameters as we are forced to do in java and c++.

2. Each time a function is called, python creates an activation record which manages list of identifiers which are in local scope of the function. In above example, count,var having local scope to the function.

3. A return statement will be the final command within the body of the function.If return is executed without explicit argument then None is returned. None will also be returned if the flow of control ever reaches the end of a function body without having executed a return statement.

4.In python,while passing information to and from a function objects are not copied. Same object is referenced by formal and actual parameters.
Both input_list and input_list_formal is referring to same list
5. when a parameter is a mutable object then that object can be modified inside body of the function. When we execute input_list_formal.append(99) inside body of the function, input_list is also
affected since formal parameter(input_list_formal) is an alias for the actual parameter(input_list).Consider following sample code and execute using python IDLE.  .
input_list = [12,2,34,56,2,4,5,6,78,12,2,3] #Total no of 2's is 3 

# Definition of countNoOf2 function 
def countNoOf2(input_list_formal):
      count= 0
      input_list_formal.append(99) # input_list_formal is modified 
      for var in input_list_formal:
            if var == 2:
                 count= count+1;
      return count

# call countNoOf2 function

print input_list # input list is: [12, 2, 34, 56, 2, 4, 5, 6, 78, 12, 2, 3]
countOf2Is = countNoOf2(input_list)
print input_list # Modified list is: [12, 2, 34, 56, 2, 4, 5, 6, 78, 12, 2, 3, 99
After executing the above sample code the Modified list will be as follows :
6.Python support default parameter values in functions.Lets's consider following function:
def fun_with_default_parameter(input1, default1='Address', default2='PhoneNo'):
      #Body of function
there are three parameters in the above function call, the last two of which offer default values. We can call the above function like :
fun_with_default_parameter(Nikhil, 'Hyderabad', '500081') # default value is overridden
fun_with_default_parameter(Ranjan) # default value is used

7.Python support Keyword Parameters in functions. Above function can be modified to use keyword parameter passing.
def fun_with_keyword_parameter(name = 'Default_name',                    
                                                      address ='default_Address', Phone='default_PhoneNo'):
      #Body of function
here all three parameters having default values.We can override specific parameters via function call like this :
fun_with_keyword_parameter(name = 'Nikhil', phone = '88888888888')
fun_with_keyword_parameter(address= 'Madhapur, Hyderabad', phone = '88888888888')

8. Python support various in built functions which makes python simple and efficient. Few of them are listed below:

9.global statement: It is possible to assign a value to a variable defined outside a function using
global statement. Lets execute following sample code to understand it :
x = 50
def fun_global):
    global x     # x is marked global
    print 'x before reassign is ', x
    x = 2
    print 'Changed global x to', x
func()
print 'Value of x after reassign inside function', x 
Outcome of above program is : 
x before reassign is 50
Changed global x to 2
Value of x after reassign inside function 2
Since, x is marked global inside fun_global() so when x is reassigned with new value 2, it is available outside function too.

Previous : Python Data Structures - Non Sequence                    Next : Python Input and Output

1 Comments

Previous Post Next Post