Functions in Python

Defining a Function

You can define functions to provide the required functionality. Here are simple rules to define a function in Python:

Example (DOC string of function):

Here is the simplest form of a Python function. This function takes a string as input parameter and prints it on standard screen.

def printme( str ):
   "This is the doc string. It is optional. Generally, a meaningful description is given here"
   print str
   return

 

DEF EXECUTE AT RUNTIME

The def is an executable statement. When it runs, it creates a new function object and assigns it to a name. Because it's a statement, a def can appear anywhere a statement can even nested in other statements:

# function.py
def func():
    print('func()')
    def func1():
        print('func1')
        def func2():
            print('func2')
        func2()
    func1()

func()

Output should look like this:

$ python function.py
func()
func1
func2

Because function definition happens at runtime, there's nothing special about the function name. What's important is the object to which it refers:

>>> def func():
    print('func()')
    def func1():
        print('func1')
        def func2():
            print('func2')
        func2()
    func1()

>>> othername = func    # Assign function object
>>> othername()         # Call func again
func()
func1
func2
>>> othername2 = func() # Call func one more time
func()
func1
func2

Here, the function was assigned to a different name and called through the new name. Functions are just object. They are recorded explicitly in memory at program execution time.

 

Calling a Function

Defining a function only gives it a name, specifies the parameters that are to be included in the function, and structures the blocks of code.

Once the basic structure of a function is finalized, you can execute it by calling it from another function or directly from the Python prompt.

Following is the example to call printme() function:

#!/usr/bin/python

# Function definition is here
def printme( str ):
   "This prints a passed string into this function"
   print str;
   return;

# Now you can call printme function
printme("I'm first call to user defined function!");
printme("Again second call to the same function");

This would produce following result:

I'm first call to user defined function!
Again second call to the same function

Pass by reference vs value

All parameters (arguments) in the Python language are passed by reference. It means if you change what a parameter refers to within a function, the change also reflects back in the calling function. For example:

#!/usr/bin/python

# Function definition is here
def changeme( mylist ):
   "This changes a passed list into this function"
   mylist.append([1,2,3,4]);
   print "Values inside the function: ", mylist
   return

# Now you can call changeme function
mylist = [10,20,30];
changeme( mylist );
print "Values outside the function: ", mylist

 

Output:

Values inside the function:  [10, 20, 30, [1, 2, 3, 4]]
Values outside the function:  [10, 20, 30, [1, 2, 3, 4]]

There is one more example where argument is being passed by reference but inside the function, but the reference is being over-written.

#!/usr/bin/python

# Function definition is here
def changeme( mylist ):
   "This changes a passed list into this function"
   mylist = [1,2,3,4]; # This would assig new reference in mylist
   print "Values inside the function: ", mylist
   return

# Now you can call changeme function
mylist = [10,20,30];
changeme( mylist );
print "Values outside the function: ", mylist

The parameter mylist is local to the function changeme. Changing mylist within the function does not affect mylist. The function accomplishes nothing and finally this would produce following result:

Values inside the function:  [1, 2, 3, 4]
Values outside the function:  [10, 20, 30]

Returning from function is also done by ref

#!/usr/bin/python

 
def Fun1(list1):
    list1.append(10)
    return list1
li = [1,2,4]
 
li2 = Fun1(li) #parameter is passed by reference. Return is also by reference
print li2  #[1,2,4,10]
Fun1(li)  #change of li will also affect li2 as both are referencing to the same object
print li  #[1,2,4,10,10]
print li2 #[1,2,4,10,10] 

Function Arguments:

You can call a function by using the following types of formal arguments::

Required arguments:

Required arguments are the arguments passed to a function in correct positional order. Here the number of arguments in the function call should match exactly with the function definition.

To call the function printme() you definitely need to pass one argument otherwise it would give a syntax error as follows:

#!/usr/bin/python

# Function definition is here
def printme( str ):
   "This prints a passed string into this function"
   print str;
   return;

# Now you can call printme function
printme("Kalyan")
printme();

 

When the above code is executed, it produces following result:

Kalyan
Traceback (most recent call last):
  File "test.py", line 11, in <module>
    printme();
TypeError: printme() takes exactly 1 argument (0 given)


Keyword arguments:

Keyword arguments are related to the function calls. When you use keyword arguments in a function call, the caller identifies the arguments by the parameter name.

This allows you to skip arguments or place them out of order because the Python interpreter is able to use the keywords provided to match the values with parameters. You can also make keyword calls to the printme() function in the following ways:

#!/usr/bin/python

# Function definition is here
def printme( str ):
   "This prints a passed string into this function"
   print str;
   return;

# Now you can call printme function
printme( str = "My string");

When the above code is executed, it produces following result:

My String

 

Following example gives more clear picture. Note, here order of the parameter does not matter:

#!/usr/bin/python

# Function definition is here
def printinfo( name, age ):
   "This prints a passed info into this function"
   print "Name: ", name;
   print "Age ", age;
   return;

# Now you can call printinfo function
printinfo( age=50, name="miki" );

When the above code is executed, it produces following result:

Name:  miki
Age  50

Default arguments:

A default argument is an argument that assumes a default value if a value is not provided in the function call for that argument. Following example gives idea on default arguments, it would print default age if it is not passed:


		
>>> def f(a, b=2, c=3):
	print(a, b, c)

>>> f(1)
1 2 3
>>> f(10, 50)
10 50 3
>>> f(10, 70, 90)
10 70 90
>>> f(10, 200)
10 200 3

*ARGS AND **KWARGS - COLLECTING AND UNPACKING ARGUMENTS

You may need to process a function for more arguments than you specified while defining the function. These arguments are called variable-length arguments and are not named in the function definition, unlike required and default arguments.

The general syntax for a function with non-keyword variable arguments is this:

def functionname([formal_args,] *var_args_tuple ):
   "function_docstring"
   function_suite
   return [expression]

An asterisk (*) is placed before the variable name that will hold the values of all nonkeyword variable arguments. This tuple remains empty if no additional arguments are specified during the function call. Following is a simple example:


		
#!/usr/bin/python
 
# Function definition is here
def printinfo( arg1, *vartuple ):  # '*' --> indicates the variable number of args
   "This prints a variable passed arguments"
   print "Output is: "
   print arg1
   for var in vartuple:
      print var
   return;
 
# Now you can call printinfo function
printinfo( 10 );
printinfo( 70, 60, 50 );
li=[4,5,6,7]
printinfo("Hello",30,*li)  #'*'--> indicates the every item in the list
 

When the above code is executed, it produces following result:


		
Output is: 
10
Output is: 
70
60
50
Output is: 
Hello
30
4
5
6
7
 
The ** is similar but it only works for keyword arguments. In other words, it collects them into a new dictionary. Actually, ** allows us to convert from keywords to dictionaries:
>>> def f(**kargs):
	print(kargs)
	
>>> f()
{}
>>> f(a=10, b=20)
{'a': 10, 'b': 20}

UNPACKING ARGUMENTS

We can use the * or ** when we call a function. In other words, it unpacks a collection of arguments, rather than constructing a collection of arguments. In the following example, we pass five arguments to a function in a tuple and let Python unpack them into individual arguments:

>>> def f(a, b, c, d, e):
	print(a, b, c, d, e)
	
>>> args = (10, 20)
>>> args += (30, 40, 50))
>>> f(*args)
10 20 30 40 50

In the same way, the ** in a function call unpacks a dictionary of key/value pairs into separate keyword arguments:

>>> kargs = {'a':10, 'b':20, 'c':30}
>>> kargs['d']=40
>>> kargs['e']=50
>>> f(**kargs)
10 20 30 40 50

Also, with various combinations:

>>> f(*(10, 20), **{'d':40, 'e':50, 'c':30})
10 20 30 40 50
>>> f(10, *(20, 30), **{'d':40, 'e':50})
10 20 30 40 50
>>> f(10, c = 30, *(20,), **{'d':40, 'e':50})
10 20 30 40 50
>>> f(10, *(20,30), d=40, e=50)
10 20 30 40 50
>>> f(10, *(20,), c=30, **{'d':40, 'e':50})
10 20 30 40 50

The Anonymous Functions:

You can use the lambda keyword to create small anonymous functions. These functions are called anonymous because they are not declared in the standard manner by using the def keyword.

Syntax:

The syntax of lambda functions contains only a single statement, which is as follows:

lambda [arg1 [,arg2,.....argn]]:expression

Following is the example to show how lembda form of function works:

#!/usr/bin/python

# Function definition is here
sum = lambda arg1, arg2: arg1 + arg2;

 

# Now you can call sum as a function
print "Value of total : ", sum( 10, 20 )
print "Value of total : ", sum( 20, 20 )

When the above code is executed, it produces following result:

Value of total :  30
Value of total :  40

The return Statement:

The statement return [expression] exits a function, optionally passing back an expression to the caller. A return statement with no arguments is the same as return None.

All the above examples are not returning any value, but if you like you can return a value from a function as follows:

#!/usr/bin/python

# Function definition is here
def sum( arg1, arg2 ):
   # Add both the parameters and return them."
   total = arg1 + arg2
   print "Inside the function : ", total
   return total;

# Now you can call sum function
total = sum( 10, 20 );
print "Outside the function : ", total 

When the above code is executed, it produces following result:

Inside the function :  30
Outside the function :  30

Scope of Variables:

All variables in a program may not be accessible at all locations in that program. This depends on where you have declared a variable.

The scope of a variable determines the portion of the program where you can access a particular identifier. There are two basic scopes of variables in Python:

Global vs. Local variables:

Variables that are defined inside a function body have a local scope, and those defined outside have a global scope.

This means that local variables can be accessed only inside the function in which they are declared whereas global variables can be accessed throughout the program body by all functions. When you call a function, the variables declared inside it are brought into scope. Following is a simple example:

#!/usr/bin/python

total = 0; # This is global variable.
# Function definition is here
def sum( arg1, arg2 ):
   # Add both the parameters and return them."
   total = arg1 + arg2; # Here total is local variable.
   print "Inside the function local total : ", total
   return total;

# Now you can call sum function
sum( 10, 20 );
print "Outside the function global total : ", total 

When the above code is executed, it produces following result:

Inside the function local total :  30
Outside the function global total :  0

Mathematical Functions:

The below functions are defined im math module.

import sys

import math

x = 2

print sys.path

y = 3;

z = pow(x,y)

print (z);

print (3.0/2);

print (3.0//2);

print math.ceil(3.4);

print (2*math.pi);