Python Programming Functions

What is function?

  • Function is reusable block of python code which performs unit of tasks.
  • Python provides lot of built in functions.
  • User can also define the own function in python program, this functions are also called user defined functions.

Rules to define function in python

  • Function begins with the keyword 'def' followed by function name and parentheses ( ).
  • Input parameters must be placed within parentheses ().
  • First statement in a function can be documentation string(docstring) or comments but it is optional one.
  • Function code block in a function starts with a colon (:).
  • Function should return value, return [value or expression] is used to exit a function and return this value in caller.
  • return statement with no return value or no return statement in a function is same as return None.
def function_name(parameter1[, parameter2, ..]):
    "comments or doc string"
     # function code
     # return statement (optional default is None)

Python Function Example

Function definition

                                                                                                                                
def get_avg_mark(name, mark1, mark2):                                              
    mark = (mark1 + mark2) / 2;                                                 
    return (name, mark);                                                        

Calling function

Function can be invoked using function name and followed by any parameters.
var_tuple = get_avg_mark('student1', 78, 87);                                                                                                                     
print var_tuple;  
Output:
$ python test_tuple.py
('student1', 82)

return None

#!/usr/bin/python                                                               
                                                                                
def show_message(msg):                                                          
    print(msg);                                                                 
    return;                                                                     
                                                                                
show_message("Welcome to python!");
Output:
$ python test_msg.py
Welcome to python!

Pass by reference

Most of the parameters (arguments) are passed by reference in python. whenever parameter is updated in function, updated parameter changes will reflect in caller function.
#!/usr/bin/python                                                               
                                                                                
def update_list(param):                                                         
   param.extend(['A', 'B', 'c']);                                               
   print "param inside function: ", param;                                      
   return                                                                       
                                                                                
list_var = [1, 2, 3];                                                           
                                                                                
print "list_var before function call: ", list_var;                              
update_list(list_var);                                                          
print "list_var after function call: ", list_var;  
Output:
$ python test_ref.py
list_var before function call:  [1, 2, 3]
param inside function:  [1, 2, 3, 'A', 'B', 'c']
list_var after function call:  [1, 2, 3, 'A', 'B', 'c']

Pass by value

if parameter is updated in function, updated changes won't reflect in caller function.
#!/usr/bin/python                                                               
                                                                                
def update_param(param):                                                        
   param = 10;                                                                  
   print "param inside function: ", param;                                      
   return                                                                       
                                                                                
int_var = 20;                                                                   
                                                                                
print "int_var before function call: ", int_var;                                
update_param(int_var);                                                          
print "int_var after function call: ", int_var;
Output:
$ python test_ref.py
int_var before function call:  20
param inside function:  10
int_var after function call:  20

Different types of parameters or arguments in function

  • Required parameters
  • Keyword parameters
  • Default parameters
  • varaible-length parameters

Required Parameters

Required parameters are mandatory parameters which need to be passed in same positional order when calling function.
#!/usr/bin/python                                                               
                                                                                
def show_message(msg):                                                          
    print(msg);                                                                 
    return;                                                                     
                                                                                
show_message(); 
Output:
$ python test_msg.py
Traceback (most recent call last):
  File "test_msg.py", line 7, in 
    show_message();
TypeError: show_message() takes exactly 1 argument (0 given)
here msg parameter is a required parameter but it is not passed when invoking, so resulting python interpreter error.
if we call function with required parameter as below, will give expected output.
                                                                    
show_message("Welcome to python!");
Output:
$ python test_msg.py
Welcome to python!

Keyword Parameters

keyword parameters in a function call, the caller identifies the parameters by the parameter name.
#!/usr/bin/python                                                               
                                                                                
def get_avg_mark(name, mark1, mark2):                                           
    mark = (mark1 + mark2) / 2;                                                 
    return mark;                                                                
                                                                                
avg= get_avg_mark(mark1=98, name = 'student1', mark2 = 77);                     
                                                                                
print avg; 
Output:
$python get_avg.py
87
here calling function using parameter name as keyword and parameter order is not important.

Default Parameters

default parameter is an argument that has a default value if a value is not provided in the function call, otherwise passed value will be used in the function.
#!/usr/bin/python                                                               
                                                                                
def get_avg_mark(name, mark1, mark2=77):                                        
    mark = (mark1 + mark2) / 2;                                                 
    return (name, mark);                                                        
                                                                                
avg= get_avg_mark(mark1=98, name = 'student1');                                 
print avg;                                                                      
avg= get_avg_mark('student2', 78, 86);                                          
print avg; 
Output:
$ python test_avg.py
('student1', 87)
('student2', 82)

Variable-length Parameters

Additional more parameters except specified in function definition are variable-length parameters. variable-length parameters are not named in the function definition.
#!/usr/bin/python                                                               

# marks parameter is the variable-length parameter which holds non specified param values are as tuples.                                                              
def get_avg_mark(name, *marks):                                                 
    mark = 0;                                                                   
    for m in marks:                                                             
        mark +=m;                                                               
    mark = mark/len(marks);                                                     
    return (name, mark);                                                        
                                                                                
avg= get_avg_mark('student1', 76, 70, 72);                                      
print avg;                                                                      
avg= get_avg_mark('student2', 78, 86, 65, 85);                                  
print avg;  
Output:
$ python test_avg.py
('student1', 72)
('student2', 78)

Privacy Policy  |  Copyright@2017 - All Rights Reserved.  |  Contact us   |  Report website issues in Github   |  Facebook page   |  Google+ page

Free online programming tutorials

Email Facebook Google LinkedIn Twitter
^