Functions in Python

Functions are blocks of reusable code that can be reused anywhere within the program. Functions tend to reduce code redundancy and make the code more modular. The usage of functions makes the code more readable as the code is divided into smaller manageable parts.

Defining a Function

In python we can define a function using the def keyword. It can be defined as follows.

def functionName( parameters ):
   function_suite
   return [expression]

Try

Calling a Function

We can call a function in python using the name of the function and passing parameters inside the parentheses

#!/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")

When the above code is executed, it produces the 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

Here, we are maintaining reference of the passed object and appending values in the same object. So, this would produce the following result −

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 and the reference is being overwritten inside the called function.

#!/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 the following result:

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

Function Arguments

There are 4 types of arguments in functions

  • Required Arguments
  • Keyword Arguments
  • Default Arguments
  • Variable-Length Arguments

Required arguments

They are arguments that are passed into the function in correct positional order. The number of arguments exactly matches with the arguments in the function definition.

#!/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()

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

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

Try

Keyword arguments

When keywords arguments are passed into a function, the caller relates the identity of the parameter through the keyword name.

#!/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 the following result −

My string

The following example gives more clear picture. Note that the order of parameters 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 the following result −

Name:  miki
Age  50

Default arguments

A default argument can assume a default value even when a value is not provided in the function call for that argument.

#!/usr/bin/python

# Function definition is here
def printinfo( name, age = 35 ):
   "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" )
printinfo( name="miki" )

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

Name:  miki
Age  50
Name:  miki
Age  35

Variable-length arguments

Sometimes in some cases we may need to process some functions that need variable length parameters.

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 holds 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 ):
   "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 )

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

Output is:
10
Output is:
70
60
50

The Anonymous Functions

Anonymous functions unlike regular functions are not declared using the def keyword. They are declared anonymously using the lambda keyword.
A few characteristics of the lambda functions are represented below
Lambda functions can take any number of arguments but return only a single value in the form of an expression.
Lambda functions cannot access variables that are not in their parameters.

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 lambda 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 the following result −

Value of total :  30
Value of total :  40

The return Statement

The return statement effectively exits from a function, passing back control and a value to the caller.

#!/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 the following result −

Inside the function :  30
Outside the function :  30

Scope of Variables

There are two different scopes possible in a variable

  • Global scope
  • Local scope

When a variable is declared within the function body, it is said to have a local scope. When the variable is declared outside the function it is said to have a global scope.

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 the following result −

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