Unit P5:
Functions
STRUCTURING YOUR CODE, FUNCTIONS,
PARAME TERS, RE TURN VALUE
Chapter 5
This Photo by Unknown Author is licensed under CC BY-SA
Politecnico di Torino COMPUTER SCIENCES 1
Unit Goals
▪ To be able to implement functions
▪ To become familiar with the concept of parameter passing
▪ To develop strategies for decomposing complex tasks into simpler
ones
▪ To be able to determine the scope of a variable
In this unit, you will learn how to design and implement your own functions
Using the process of stepwise refinement, you will be able to break up complex tasks
into sets of cooperating functions
Politecnico di Torino COMPUTER SCIENCES 2
Functions as
Black Boxes 5.1
Politecnico di Torino COMPUTER SCIENCES 3
Functions as Black Boxes
▪ A function is a sequence of instructions with a name
▪ For example, the round function contains instructions to round a
floating-point value to a specified number of decimal places
https://docs.python.org/3/library/functions.html#round
Politecnico di Torino COMPUTER SCIENCES 4
Calling Functions
▪ You call a function in order to execute its instructions
price = round(6.8275, 2) # Sets price to 6.83
▪ By using the expression round(6.8275, 2), your program calls
the round function, asking it to round 6.8275 to two decimal digits
Politecnico di Torino COMPUTER SCIENCES 5
Calling Functions (2)
▪ You call a function in order to execute its instructions
price = round(6.8275, 2) # Sets price to 6.83
▪ By using the expression round(6.8275, 2), your program calls
the round function, asking it to round 6.8275 to two decimal digits
▪ When the function terminates, the computed result is returned by
the function and may be used in an expression (e.g., assigned to
price)
▪ After the value has been used, your program resumes execution
Politecnico di Torino COMPUTER SCIENCES 6
Calling Functions (3)
price = round(6.8275, 2) # Sets result to 6.83
This is not our code!
The function is defined
in the standard library.
Politecnico di Torino COMPUTER SCIENCES 7
Function Arguments
▪ When another function calls the round function, it provides
“inputs”, such as the values 6.8275 and 2 in the call
round(6.8275, 2)
▪ These values are called the arguments of the function call
o Note that they are not necessarily inputs provided by a human user
o They are the values for which we want the function to compute a result
▪ Functions can receive multiple arguments
▪ It is also possible to have functions with no arguments
Politecnico di Torino COMPUTER SCIENCES 8
Function Return Value
▪ The “output” that the round function computes is called the return
value
▪ Functions return only one value
o For multiple values, return a list or a tuple (see later…)
o Some functions do not return any value
▪ The return value of a function is returned to the point in your
program where the function was called
price = round(6.8275, 2)
▪ When the round function returns its result, the return value is
stored in the variable ‘price’
Politecnico di Torino COMPUTER SCIENCES 9
The round Function as a Black Box
▪ Use functions like ‘black boxes’
o Pass the function what it needs to do its job
o Receive the answer
▪ Don’t need to know how they are implemented!
▪ Real-life analogy: A thermostat is a ‘black box’
o Set a desired temperature
o Turns on heater or AC (Air Conditioner) as required
o You don’t have to know how it really works!
• How does it know the current temp?
• What signals/commands does it send to the heater or AC?
Politecnico di Torino COMPUTER SCIENCES 10
The round Function as a Black Box
▪ You may wonder… how does the round function perform its job ?
▪ As a user of the function, you don’t need to know how the function
is implemented
▪ You just need to know the specification of the function:
o If you provide arguments x and n, the function returns x rounded to n
decimal digits
▪ When you design your own functions, you will want to make them
appear as black boxes
o Even if you are the only person working on a program, you want to use
them as simple black boxes in the future, and let other programmers do the
same
Politecnico di Torino COMPUTER SCIENCES 11
Where to Find Library Functions (1)
▪ Built-In functions in the Standard Library
o https://docs.python.org/3/library/functions.html
Important
(already used)
useful
(take a look)
will use later
(with lists, dicts)
Politecnico di Torino COMPUTER SCIENCES 12
Where to Find Library Functions (2)
▪ Inside Modules in the Standard Library
o https://docs.python.org/3/library/
o https://docs.python.org/3/py-modindex.html
o More than 200 modules, with many functions in each
o Interesting ones: string, math, random, statistics, csv, json, …
▪ Remember to import:
import module
▪ Or:
from module import function
▪ Thousands of extra modules (not in the standard library) can be
downloaded and installed if needed (not used in this course…)
Politecnico di Torino COMPUTER SCIENCES 13
Summary
Function call
x z = f(x, 3.5)
Inputs
4 (arguments)
4
f
(library function or
function written by us)
3.5 3.5 Output
(return
value)
Politecnico di Torino COMPUTER SCIENCES 14
Implementing and
Testing Functions 5.2
Politecnico di Torino COMPUTER SCIENCES 15
Implementing Functions
Besides using existing functions, it is useful to be able to
create new ones…
We have to define two key elements
1. Interface:
• Function name, arguments, return value
2. Implementation:
• What does the function do
• Instructions to produce the output given the arguments…
Then, we will be able to use (call) the function.
Politecnico di Torino COMPUTER SCIENCES 16
Example:
▪ A function to calculate the volume of a cube
o What does it need to do its job?
o What does it answer with?
▪ When writing (‘defining’) this function
o Pick a name for the function (cubeVolume)
o Define a variable name for each incoming argument
• (sideLength) – list of parameter variables
o Put all this information together along with the def keyword to form the
first line of the function’s definition:
This line is called the
def cubeVolume(sideLength): header of the function
Politecnico di Torino COMPUTER SCIENCES 17
Implementing the Cube Function
▪ The def keyword starts a new block of code (compound instruction).
▪ Inside this block, we will write the instructions that compose the function
body (implementation)
Function Body
def cubeVolume(sideLength) :
volume = sideLength ** 3
return volume
▪ Inside the body, the arguments can be used as normal variables.
▪ If the function needs to return a result to the caller, we add the instruction:
return <value>
Politecnico di Torino COMPUTER SCIENCES 18
Syntax: Function Definition
Politecnico di Torino COMPUTER SCIENCES 19
Testing (Using) a Function
▪ If you run a program containing just the function definition, then
nothing happens
o After all, nobody is calling (using) the function
▪ In order to use the function, your program should contain
o The definition of the function
o Statements that call the function and use the result
Politecnico di Torino COMPUTER SCIENCES 20
Calling/Testing the Cube Function
Implementing the function (function definition)
def cubeVolume(sideLength) :
volume = sideLength ** 3
return volume
Calling/testing the function
result1 = cubeVolume(2)
result2 = cubeVolume(10)
print("A cube with side length 2 has volume", result1)
print("A cube with side length 10 has volume", result2)
Print("A cube with side length 4 has volume”, cubeVolume(4))
Politecnico di Torino COMPUTER SCIENCES 21
Calling a Function Let’s test it with
the debugger!!
Caller code
result1 = cubeVolume(2)
1) The provided value is used to
initialize the parameter
(e.g., sideLength = 2)
The actual funtion
def cubeVolume(sideLength) :
volume = sideLength ** 3
return volume
3) The returning value is 2) The function Body is
returned back to the point executed using the current
where the function was value of the variable
called
Politecnico di Torino COMPUTER SCIENCES 22
Using Functions: Order (1)
▪ It is important that you define any function before you call it
▪ For example, the following will produce a compile-time error:
print(cubeVolume(10))
def cubeVolume(sideLength) :
volume = sideLength ** 3
return volume
▪ The compiler does not know that the cubeVolume function will be
defined later in the program
o Doesn’t know what function to call
Politecnico di Torino COMPUTER SCIENCES 23
Using Functions: Order (2)
▪ However, a function can be called from within another function before the
former has been defined
▪ The following is perfectly legal:
def main() :
result = cubeVolume(2) # 1
print("A cube with side length 2 has volume",
result)
def cubeVolume(sideLength) :
volume = sideLength ** 3
return volume
main() # 2
▪ In #1, the function main is just defined (not yet executed). It will be called in
#2, that is after the definition of cubeVolume.
Politecnico di Torino COMPUTER SCIENCES 24
Parameter Passing 5.3
Politecnico di Torino COMPUTER SCIENCES 25
Parameter Passing
▪ Parameter variables (called formal parameters) receive the
argument values (effective or actual parameters) supplied in the
function call
▪ The argument value may be: Calling function
o The current contents of a variable o
Argument value
o A ‘literal’ value: 2, 3.14, 'hello' u
t
▪ The parameter variable is: Parameter variable in
o Initialized with the value of the argument value
Called function
o Used as a variable inside the called function
Politecnico di Torino COMPUTER SCIENCES 26
Parameter Passing Steps
result1 = cubeVolume(2)
def cubeVolume(sideLength):
volume = sideLength * 3
return volume
See it live on PythonTutor:
http://pythontutor.com/live.html#mode=edit
Politecnico di Torino COMPUTER SCIENCES 27
Arguments when calling Functions
Call Call
result1 = cubeVolume(2) result1 = cubeVolume(size)
Call
Argument: variable
result1 = cubeVolume(a**2+b**2) sideLength = size
Argument: literal
sideLength = 2 Argument: expression
sideLength = a**2+b**2
Called function
def cubeVolume(sideLength) :
volume = sideLength ** 3
return volume
Politecnico di Torino COMPUTER SCIENCES 28
Common Error
total = 10
▪ Trying to modify parameter variables addTax(total, 7.5)
total
▪ For many types of data, modifying the value
10.0
of a parameter Variable will not affect the
caller.
def addTax(price, rate):
o IMMUTABLE: int, float, string, tuples… tax = price * rate / 100
o When we modify the value inside the function, # No effect outside the function
we’re effectively creating a new copy price = price + tax
price
10.75
▪ Example:
o Called function (addTax) modifies price
o The total variable in the caller function is
unaffected
o total remains equal to 10 after the function call
Politecnico di Torino COMPUTER SCIENCES 29
Programming Tip
▪ Do not modify parameter variables
▪ Many programmers find this practice confusing
def totalCents(dollars, cents) :
cents = dollars * 100 + cents # Modifies parameter variable.
return cents
▪ To avoid the confusion, simply introduce a separate variable:
def totalCents(dollars, cents) :
result = dollars * 100 + cents
return result
Politecnico di Torino COMPUTER SCIENCES 30
Return Values 5.4
Politecnico di Torino COMPUTER SCIENCES 31
Return Values
▪ Functions can return one value (or no values)
o Add a return statement that returns a value
o A return statement does two things:
• Immediately terminates the function
• Passes the return value back to the calling function
def cubeVolume (sideLength):
volume = sideLength * 3
return volume
return statement
The return value may be a value, a variable or the result of an expression
Politecnico di Torino COMPUTER SCIENCES 32
Returning multiple values
▪ Only one value may be returned by a function
▪ If you need to return more than one value, you may return a tuple,
containing the values
▪ Example:
o return (x, y)
o Build a tuple (x, y)
o Return it
Politecnico di Torino COMPUTER SCIENCES 33
Multiple return Statements
▪ A function can use multiple return statements
o But every branch should lead the function to encounter a return
statement
def cubeVolume(sideLength):
if (sideLength < 0):
return 0
return sideLength * 3
Politecnico di Torino COMPUTER SCIENCES 34
Multiple return Statements (2)
▪ Alternative to multiple returns (e.g., one for each branch):
• Storing the function result in a variable
• Returning the variable’s value in the last statement of the function
o For example:
def cubeVolume(sideLength) :
if sideLength >= 0:
volume = sideLength ** 3
else :
volume = 0
return volume
Politecnico di Torino COMPUTER SCIENCES 35
Make Sure a Return Catches All Cases
▪ Missing return statement
o Make sure all conditions are handled
o In this case, sideLength could be less than 0
• No return statement for this condition
o It may result in a run-time error because Python returns the
special value None when you forget to return a value
def cubeVolume(sideLength) :
if sideLength >= 0 :
return sideLength ** 3
# Error—no return value if sideLength < 0
Politecnico di Torino COMPUTER SCIENCES 36
Exercise
Let’s build a function to determine if its argument is a prime
number
Let’s use the algorithm seen in class and “encapsulate” it in a
function called: prime()
Politecnico di Torino COMPUTER SCIENCES 37
Functions Without
Return Values 5.5
Politecnico di Torino COMPUTER SCIENCES 38
Functions Without Return Values
▪ Functions are not required to return a value
o Typical example: functions that print something to the console
▪ In this case, you can use a return statement without value
return # no value specified
▪ Or omit the return keyword. If the return keyword is not
encountered during the execution of a function, it is equivalent to
having an empty return after the last statement of the function
Politecnico di Torino COMPUTER SCIENCES 39
Using return Without a Value
▪ Example:
Definition
def boxString(contents) : Call
n = len(contents) : ...
print("-" * (n + 2)) boxString("Hello")
print("!" + contents + "!") ...
print("-" * (n + 2))
return
Result
No return in the function is equivalent to a
return in the last line.
Politecnico di Torino COMPUTER SCIENCES 40
Using return Without a Value
The return keyword without a value can be used also in other
places in the function
o The function will terminate immediately!
def boxString(contents) :
n = len(contents)
if n == 0 :
return # Terminates immediately
print("-" * (n + 2))
print("!" + contents + "!")
print("-" * (n + 2))
Politecnico di Torino COMPUTER SCIENCES 41
The main function 5.2
Politecnico di Torino COMPUTER SCIENCES 42
The main Function
▪ When defining and using functions in Python, it is good
programming practice to place all statements into functions, and to
specify one function as the starting point
▪ Any legal name can be used for the starting point, but we chose
‘main’ (by convention) since it is the mandatory function name
used by other common languages (C/C++)
▪ Of course, we must have one statement in the program that calls
the main function
Politecnico di Torino COMPUTER SCIENCES 43
Syntax: The main Function
Politecnico di Torino COMPUTER SCIENCES 44
Exercise
▪ Given two integers n, m, given as input, compute their binomial
coefficient C(n, m)
▪ Analysis:
o Formula: C(n,m) = n! / (m! * (n-m)!)
o How do we compute the factorial?
• Definition n! = n * (n-1) *.... * 1
o Constraint: we must have n>m
▪ Let’s build:
o A function fact(x) to compute the factorial
o A function binom(x,y) to compute the binomial coefficient
o A main() function.
Politecnico di Torino COMPUTER SCIENCES 45
Variable Scope 5.8
Politecnico di Torino COMPUTER SCIENCES 46
Variable Scope
▪ Variables can be declared:
o Inside a function
• Known as ‘local variables’
• Only available inside this function
• Parameter variables are like local variables
o Outside of a function
• Sometimes called ‘global scope’
• Can be used (and changed) by code in any function
▪ How do you choose?
The scope of a variable is the part of
the program in which it is visible
Politecnico di Torino COMPUTER SCIENCES 47
Examples of Scope
o sum, square & i are local variables in main
def main() :
sum = 0
for i in range(11) : sum
square = i * i i
sum = sum + square
print(square, sum)
square
Politecnico di Torino COMPUTER SCIENCES 48
Local Variables of functions
▪ Variables declared inside one function are not visible to other
functions
o sideLength is local to main
o Using it outside main will cause a compiler error
def main():
sideLength = 10
result = cubeVolume()
print(result)
def cubeVolume():
return sideLength * sideLength * sideLength # ERROR
Politecnico di Torino COMPUTER SCIENCES 49
Re-using Names for Local Variables
▪ Variables declared inside one function are not visible to other
functions
o result is local to square and result is local to main
o They are two different variables and do not overlap, even if they have the
same name
def square(n):
result = n * n result
return result
def main():
result = square(3) + square(4) result
print(result)
Politecnico di Torino COMPUTER SCIENCES 50
Global Variables
▪ They are variables that are defined outside functions
▪ A global variable is visible to all functions
▪ However, any function that wishes to change a global variable
must include a global declaration
Not a good idea…
better avoid it
Politecnico di Torino COMPUTER SCIENCES 51
Example Use of a Global Variable
▪ If you omit the global declaration, then the balance variable
inside the withdraw function is considered a local variable
balance = 10000 # A global variable
def withdraw(amount) :
# This function intends to access the
# global ‘balance’ variable
global balance
if balance >= amount :
balance = balance - amount
Politecnico di Torino COMPUTER SCIENCES 52
Programming Tip
▪ There are a few cases where global variables are required (such as
pi defined in the math module), but they are quite rare
▪ Programs with global variables are difficult to maintain and extend
because you can no longer view each function as a “black box”
that simply receives arguments and returns a result
▪ Instead of using global variables, use function parameter variables
and return values to transfer information from one part of a
program to another
Politecnico di Torino COMPUTER SCIENCES 53
Stepwise
Refinement 5.7
Politecnico di Torino COMPUTER SCIENCES 54
Stepwise Refinement
▪ To solve a difficult task, break it down into simpler tasks
▪ Then keep breaking down the simpler tasks into even simpler
ones, until you are left with tasks that you know how to solve
Politecnico di Torino COMPUTER SCIENCES 55
Example
▪ Write a program that generates a random password with a
specified length
▪ The password must contain at least 1 digit and 1 special character:
o For simplicity, let’s decide it will contain exactly one digit and one special
character.
o Assume that special characters are + – * / ? ! @ # $ % &
▪ The other characters will be letters, and again for simplicity, we’ll
use only lowercase letters from the English alphabet.
Politecnico di Torino COMPUTER SCIENCES 56
Program Structure
▪ How do we proceed?
o Organize the problem as a set of sub-problems
o Solve each sub-problem with a function
▪ main()
o Read the desired length of the password l
o Create the password
o Print it
▪ Create the password: makePassword()
o Generate a random sequence of lowercase letters of length l → function initPassword()
o Replace one of the characters (in a random position) with a random special character
o Replace one of the characters (in a random position) with a random digit
Politecnico di Torino COMPUTER SCIENCES 57
Example
▪ Some problems are repeated:
o Draw a random character from a set (repeated 3 times)
• Let’s code a function randomCharacter() that selects a random character from a string
• Use the function 3 times (for letters, digits and special characters)
o Insert a character in a random position of a string (repeated 2
times)
• Function insertAtRandom() that:
• Draws a random index (in the valid range!!!)
• “Replaces” the character at that index
• The most difficult of the functions
Politecnico di Torino COMPUTER SCIENCES 58
Example
initPassword
o Create an empty string password.
o Generate l random lowercase letters and add them to password.
Politecnico di Torino COMPUTER SCIENCES 59
Example
randomCharacter
o Draw a random character from a string
o Equivalent to drawing an index (in the valid range) and returning the
character at that index.
Politecnico di Torino COMPUTER SCIENCES 60
Example
insertAtRandom
o Why is it more difficult than it seems?
• Generate an index in the range [0, len()-1]
• REPLACE the character at that position with a random one.
▪ But strings are immutable!!!!
▪ I cannot just overwrite characters!
▪ Solution:
▪ Create a new string
▪ Initialize it to the original string up to the selected index
▪ Append the new random character
▪ Append the rest of the string.
Politecnico di Torino COMPUTER SCIENCES 61
Programming Tips
▪ Keep functions short
o If more than one screen, break into ‘sub’ functions
▪ Use Stubs as you write larger programs
o A function that returns a simply calculated value (even wrong, or always the
same), enough to test the function as soon as possible, in the context in
which it is called
o They are used to understand if the sequence of calls "works"
Politecnico di Torino COMPUTER SCIENCES 62
Summary
Politecnico di Torino COMPUTER SCIENCES 63
Summary: Functions
▪ A function is a named sequence of instructions
▪ Arguments are supplied when a function is called
▪ The return value is the result that the function computes
▪ When declaring a function, you provide a name for the function
and a variable for each argument
▪ Function comments explain the purpose of the function, the
meaning of the parameters and return value, as well as any special
requirements
▪ Parameter variables hold the arguments supplied in the function
call
Politecnico di Torino COMPUTER SCIENCES 64
Summary: Function Returns
▪ The return statement terminates a function call and yields the
function result
▪ Use the process of stepwise refinement to decompose complex
tasks into simpler ones
o When you discover that you need a function, write a description of the parameter variables
and return values
o A function may require simpler functions to carry out its work
Politecnico di Torino COMPUTER SCIENCES 65
Summary: Scope
▪ The scope of a variable is the part of the program in which the
variable is visible
o Two local or parameter variables can have the same name, provided that their scopes do
not overlap
o You can use the same variable name within different functions since their scope does not
overlap
o Local variables declared inside one function are not visible to code inside other functions
Politecnico di Torino COMPUTER SCIENCES 66
Thanks
▪ Part of these slides are [edited versions] of those originally made
by Prof Giovanni Squillero (Teacher of Course 1)
Politecnico di Torino COMPUTER SCIENCES 67
License
▪ These slides are distributed under the Creative Commons license
“Attribution - Noncommercial - ShareAlike 2.5 (CC BY-NC-SA 2.5)”
▪ You are free:
o to reproduce, distribute, communicate to the public, exhibit in public, represent,
perform and recite this work
o to modify this work
▪ Under the following conditions:
o Attribution — You must attribute the work to the original authors, and you must
do so in a way that does not suggest that they endorse you or your use of the
work.
o Non-Commercial — You may not use this work for commercial purposes.
o Share Alike — If you alter, transform, or build upon this work, you may distribute
the resulting work only under the same or equivalent license as this one.
▪ http://creativecommons.org/licenses/by-nc-sa/2.5/it/
Politecnico di Torino COMPUTER SCIENCES 68