Python Functions

A function is a block of organized, reusable code that helps to perform a single, related action. Functions provide the best modularity for your application and a high degree of code reusing.

As you know, Python provides many built-in functions such as print(), etc. but you can also create your own functions according to your requirements. These functions are known as user-defined functions.

Defining a Function

Functions can be defined to provide the required functionality. Let's study the basic rules to define a function in Python described as follows:

  • Function blocks start with the keyword def followed by the function name and parentheses ( ( ) ).

  • Any input parameters or arguments should be placed within these parentheses. Parameters can also be defined inside these parentheses.

  • The first statement of a function can be an optional statement -either the documentation string of the function or docstring.

  • The code block within every function begins with a colon (:) and is indented.

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

Syntax

def functionname( parameters ):
   "function_docstring"
   function_suite
   return [expression]

By default, parameters have a positional behavior and its necessary to inform them in the same order that they were defined.

Illustration:

The following given function takes string as input parameter and prints it on standard screen.

def printme( str ):
   "This prints a passed string into this function"
   print str
   return

Calling a Function

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

Once the basic structure of a function is decided, it can be executed  by calling it from another function or directly from the Python prompt. Following is the illustration 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")

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

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

Pass by reference vs value

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

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

In this, we are maintaining a reference of the passed object and appending values in the same object. So, this would generate the result as follows −

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 illustration where the 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 influence mylist. The function achieves nothing and lastly, this would generate the result as follows −

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

Function Arguments

You can call a function with the help of the following kinds of formal arguments −

  • Required arguments
  • Keyword arguments
  • Default arguments
  • Variable-length arguments

Required arguments

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

To call the function printme(), you certainly need to pass one argument, otherwise, it provides a syntax error as below−

#!/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 implemented, it generates the following result −

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 associated with the function calls. When you use keyword arguments in a function call, the caller recognizes the arguments by the parameter name.

This permits you to skip the arguments or keep them out of order as the Python interpreter is able to use the keywords given to match the values with parameters. Keyword calls can be made to the printme() function in various ways as below −

#!/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 generates the result as follows−

My string

The following illustration explains 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 generates the result as follows −

Name:  miki
Age  50

Default arguments

A default argument is an argument that considers a default value if a value is not given in the function call for that argument. The following illustration gives an opinion on default arguments, it prints default age if it is not passed −

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

Name:  miki
Age  50
Name:  miki
Age  35

Variable-length arguments

It is required to process a function for more arguments than you specified while defining the function. These arguments are known as variable-length arguments and are not named in the function definition, unlike needed and default arguments.

The syntax for a function with non-keyword variable arguments is written below −

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

An asterisk (*) is placed prior to the variable name that involves the values of all non-keyword variable arguments. This tuple remains vacant if no additional arguments are specified during the function call. Basic illustration for this described as follows −

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

Output is:
10
Output is:
70
60
50

The Anonymous Functions

These functions are known as anonymous as they are not declared in the standard manner by using the def keyword. lambda keyword can be used to create small anonymous functions.

  • Lambda forms can take any number of arguments but return only one value in the form of expression. Commands or multiple expressions cannot be contained in this form.

  • An anonymous function cannot be a direct call to print as lambda needs an expression

  • Lambda functions have their own local namespace and cannot access variables other than those in their parameter list and those in the global namespace.

  • Although it seems that lambda is a one-line version of a function, they are not equivalent to inline statements in C or C++, whose main purpose is bypassing function stack allocation during invocation for performance reasons.

Syntax

The syntax of lambda functions consists only a single statement, written as below−

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

Following is the illustration to explain 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 generates the 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 similar to the return None.

All the above illustrations are not returning any value. You can return a value from a function as below −

#!/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 generates the 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 the place where you have declared a variable.

The scope of a variable determines the portion of the program where you can access a particular identifier. Two basic scopes of variables in Python are follows −

  • Global variables
  • Local variables

Global vs. Local variables

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

This defines 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 the basic illustration −

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

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