A function is a named subprogram (subroutine) that can be called within the program to trigger the execution of the sequence of instructions that make up the body of the function.
Values can be passed to a function by declaring parameters in its definition.
The values passed to the function, called arguments, will be assigned to these parameters.
A function can return a result to the calling program.
Python provides the following types of functions:
Syntax
def functionname( parameters ) : # function body statement(s) return [expression] |
The return
statement is used to return a result to the calling program.
Example: Write a function that returns a random integer between 0
and 100
.
import random # Function definition def random_int() : return int ( 100 * random.random()) # Function call print (random_int()) |
To pass values to a function, formal parameters are declared in the function definition.
The values passed to the function, called arguments or actual parameters, will be assigned to these formal parameters.
Example: write a function that returns a random integer between 0
and a given value.
import random # Function definition with one parameter def random_int(n) : return int (n * random.random()) # Function call with an argument print (random_int( 50 )) |
A default value can be assigned to an argument passed to a function.
Example
import random # Function definition def random_int(n = 100 ) : return int (n * random.random()) # Function call print (random_int()) print (random_int( 10 )) |
With a keyword argument, the argument is assigned based on the name of the formal parameter.
This allows you to skip arguments or place them out of order.
Example: Write a function that returns a random integer between two given values.
import random # Function definition def random_int( min , max ) : return int ( min + ( max - min ) * random.random()) # Function call print (random_int( max = 20 , min = 10 )) |
In this case, the position of the arguments does not matter.
Sometimes, we do not know in advance the number of arguments that will be passed to a function.
To handle this kind of situation, we use arbitrary arguments.
Arbitrary arguments allow us to pass a variable number of values during a function call.
We use an asterisk ( *
) before the name of the formal parameter to designate this type of argument.
The sequence of arbitrary arguments passed to a function is considered a tuple
, and thus we can iterate over its elements in a for
loop.
Example: writing a function that returns the average of several values.
# Function definition def mean( * numbers) : result = 0 for num in numbers : result + = num / len (numbers) return result # function call with 4 arguments print (mean( 1 , 2 , 3 , 4 )) |
A variable declared in the body of a function is called a local variable.
Such a variable exists only during the execution of this function, and is only used by this function.
The main program does not have access to a local variable of a function.
A function does not have access to a local variable of another function.
A variable declared in the main program is called a global variable. It exists during the entire execution of the program and is accessible everywhere.
A variable local to a function and having the same name as a global variable, hides the global variable during the execution of this function.
A nonlocal variable is used in nested functions.
Its local scope is not defined. This means that the variable can be neither in the local scope nor in the global scope.
Example: nonlocal variable.
# parent function def outer(): message = 'local' # nested function def inner(): # declare nonlocal variable nonlocal message message = 'nonlocal' print ( 'inner: ' , message) # call of nested function inner() print ( 'outer: ' , message) # call parent function outer() |
The nonlocal
variable named message
in the inner()
function has the same name as a local variable in the outer()
function.
If the value of the nonlocal
variable changes, then that change affects the local variable.
Parameter passing (or parameter transmission) refers to the mechanism by which arguments (actual parameters) are assigned to the formal parameters of a function when the function is called.
A parameter is transmitted either by value or by reference.
The behavior of the function depends on the non-mutable or mutable nature of the variable passed as an argument to the function.
Mutable variables
list
dict
set
Non-mutable variables
Nombrestuple
str
We can add elements to a variable of type list
, dict
or set
.
Thus, the length of the variable changes, and the variable is said to be mutable.
The function uses parameter passing by value when the variable passed as an argument is immutable, for example a numeric variable.
In the function call statement, the argument is a value, variable, or expression that is evaluated at the time the function is called.
When a numeric variable is passed as an argument and the function then changes the value of the formal argument, it actually creates a new variable in memory, leaving the original variable unchanged.
Example
def func(arg) : arg = arg + 1 print ( 'arg inside: ' , arg) var = 10 func(var) print ( 'var: ' , var) |
The function uses parameter passing by reference when the variable passed as an argument is mutable, for example a variable of type list
.
In the function call statement, the argument is a variable whose value is likely to be modified by the function.
When a variable of type list
is passed as an argument and the function then modifies the value of the formal parameter, this change is reflected in this variable.
Example: append an element to a list.
def append_to(num, target = []): target.append(num) return target original_list = [ 1 , 2 , 3 ] new_list = append_to( 4 , original_list) print (original_list) |