What is a function
• a function is a subprogram, that can process data and return a value • functions:
1. inbuilt Python functions
• are a part of the Python interpreter, supplied for your use • e.g. the function print(…)
2. your own functions (i.e. functions written by a programmer)
• almost each program (regardless of a programming language) contains some programmer-defined functions
Definition of a function
• a function must be defined prior its usage in a program • an example: a function calculating an area of a rectangle
def calculate_area(length, width): area = length * width
return area
• the function calculate_area
• takes two arguments – a length and a width of a rectangle • returns an area of the rectangle
arguments = an information passed into a function return value = an information returned from a function
Definition of a function
def calculate_area(length, width): area = length * width
return area
• a definition consists of two parts:
1. head of the function (first line) containing (in this order):
• the keyword def • name of the function
• a list of arguments in round brackets • a colon
2. body of the function
• sequence of statements, all statements are indented
Call of a function
# definition
def calculate_area(length, width): area = length * width
return area
# usage
l = int(input("enter a length: ")) w = int(input("enter a width: "))
a = calculate_area(l, w) # call of a function
print("area is", a)
• a function is called by writing its name followed by its arguments in round brackets
• the following program asks a user to enter the length and width of rectangle and calls a function to calculate its area
What happens when a function is called?
• normally a program is executed line by line by the interpreter (Python)
• when a function call is encountered, the Python pauses the execution of the main thread and makes a branch into the body of the function
• when the function finishes, the execution continues on the next line of the program • note that a function can call another function
# program statement 1 statement 2 function(...) statement 3 statement 4 ... # function def function(...): statement 1 statement 2 statement 3
The return statement
return expression
• returns a value from a function
# definition – the function returns larger from two numbers
def maximum(a, b): if a > b:
return a else:
return b
# function call in a program
larger = maximum(x, y)
• when a function reaches a return statement, it finishes immediately (remaining statements, if any, are skipped)
Functions returning no value
# definition def draw_line(length): for i in range(length): print("-", end = "") # call draw_line(15)• in fact, such functions return None
• they do not need contain a return statement
• function can use a return statement to finish before the end of its body
def function(...): statement if condition: return statement statement
# definition
def caution():
print("Be aware, the computer has no brain!!!")
# call
caution()
• a definition and a function call must include (empty) round brackets
Functions without arguments
Formal arguments
import math
def area(radius): # the name radius is self-explaining
return math.pi * radius * radius
def area(x): # what is the meaning of x? (radius, diameter...)
return math.pi * x * x
• a head of the function presents the formal arguments • formal arguments
• inform about the number and meaning of arguments • they should have self-explaining names
Actual arguments
• = arguments used within a function call
• in general the actual arguments are Python expressions:
a = area(5) # a constant
a = area(x) # a variable
a = area(3 * x + 5) # an arithmetic expression
a = area(x > 3) # a logical expr., evaluates to 1(True) or 0(False)
Global and local variables
• each variable has its lifetime, which defines where in the program is the variable accessible and available
• variables:
1. global
• defined outside any function
• accessible anywhere in the program
2. local
• defined inside a function
• exist (and are accessible) only in the function where they was defined • deleted when the function finishes
Global and local variables
# global variable
glob = "global variable" def function():
# local variable
loc = "local variable"
# both variables are available in the function
print(glob) print(loc)
# function call (prints both variables)
function()
# only the global variable is available outside the function
print(glob)
Change of global variable inside the function
def function():
glob = "new value of glob" print(glob)
glob = "global variable"
function() # prints: new value of glob
print(glob) # prints: global variable
• this way does not work:
a new local variable (with the same name as the global variable) is created and
hides the global variable in the function
def function(): global glob
glob = "new value of glob" print(glob)
glob = "global variable"
function() # prints: new value of glob
print(glob) # prints: new value of glob
Passing arguments by value
def increase(x): x = x + 1 print("in function:", x) x = 5 print(x) # prints: 5increase(x) # prints: in function: 6
print(x) # prints: 5
• arguments passed into a function are stored as local variables in the function ⇒ if a variable is passed in this way, its value is copied to the local variable • whatever you do with arguments you do in fact with these local copies
⇒ changes of arguments do not affect passed variables outside the function • this mechanism is called "passing by value "
Passing arguments by reference
def change(x): x[0] = 555 print("in function:", x) x = [1, 2, 3] print(x) # prints: [1, 2, 3]change(x) # prints: in function: [555, 2, 3]
print(x) # prints: [555, 2, 3]
• only a reference to the variable is passed to the function
• the reference is stored in a local variable, but both references (original outside the function and the local copy) point to the same variable
• the changes made in the function affect the variable outside the function
This holds for: list, dictionary, set
Assigning a new value to the passed reference
def change(x): x = [4, 5, 6] print("in function:", x) x = [1, 2, 3] print(x) # prints: [1, 2, 3]change(x) # prints: in function: [4, 5, 6]
print(x) # prints: [1, 2, 3]
• if you assign a new variable to the passed reference, the change will not appear outside the function (because the reference itself is stored in a local variable)
Positional arguments
def function(x, y, z): print("argument x:", x) print("argument y:", y) print("argument z:", z) function(3, 5, 1)• up to now, all arguments we used were positional • positional arguments
• have no default values
• are passed to a function according to their position in the list of arguments • cannot be omitted when the function is called
(otherwise an error occures)
argument x: 3 argument y: 5 argument z: 1
Positional arguments
def function(a, b, c): print("argument a:", a) print("argument b:", b) print("argument c:", c) function(b = 1, c = 2, a = 3)• do not need to be passed in a given order, but in such case it is necessary to call them through their names with the assignment operator
argument a: 3 argument b: 1 argument c: 2
Keyword arguments
def function(x = 1, y = 2, z = 3): print("argument x:", x) print("argument y:", y) print("argument z:", z) function() function(y = 5, z = 44, x = 0) function(z = 7)• have default values
• if they are omitted within the function call, their default values are used
• do not need to be passed in a given order (then we call them through their names)
argument x: 1 argument y: 2 argument z: 3 argument x: 0 argument y: 5 argument z: 44 argument x: 1 argument y: 2 argument z: 7
Mixing positional and keyword arguments
def function(a, b, c = 10, d = 11): print("argument a:", a) print("argument b:", b) print("argument c:", c) print("argument d:", d)• positional and keyword arguments can be mixed in one function
• the rule: positional arguments must be declared before keyword arguments
• within the function call - the arguments are passed in left to right order
function(1, 2) function(1, 2, 3) function(1, 2, d = 3) argument a: 1 argument b: 2 argument c: 10 argument d: 11 argument a: 1 argument b: 2 argument c: 3 argument d: 11 argument a: 1 argument b: 2
Function with arbitrary number of arguments
def function(*param): i = 0 for p in param: print("argument {}: {}".format(i, p)) i += 1 function(5, 7, "hello")• useful when we do not know in advance how many arguments will be passed • we use an argument with an asterisk (*) before its name: *argument
• all passed arguments are stored as a tuple
argument 0: 5 argument 1: 7
argument 2: hello
• note that an arbitrary argument must be declared behind the positional arguments: def function(x, y, *z):
Function itself is an object
def func(x):
print(2 * x)
func(7) # function call
new_ref = func # new reference
del func # deleting original reference
new_ref(4) # using the new reference
• we can assign a function to another variable
(it means we can create a new reference to the function) • we can also delete any reference to the function
output: 14 8
Why do we write function
1. repeated usage of code in the program• we do not need copy the same code in several places 2. clear program structure
• the aim is to split an overall task into several smaller tasks
• the program consists of function calls, functions only pass their results from one to another
• properly designed functions make the program well manageable • functions itself should
• be short
• do clearly defined tasks • have an appropriate name