05-Unit P5 - Functions
05-Unit P5 - Functions
05-Unit P5 - Functions
Functions
STRUCTURING YOUR CODE, FUNCTIONS,
PARAME TERS, RE TURN VALUE
Chapter 5
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
https://docs.python.org/3/library/functions.html#round
▪ 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
useful
(take a look)
4
f
(library function or
function written by us)
3.5 3.5 Output
(return
value)
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
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.
def cubeVolume(sideLength):
volume = sideLength * 3
return volume
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
return statement
def cubeVolume(sideLength):
if (sideLength < 0):
return 0
return sideLength * 3
o For example:
def cubeVolume(sideLength) :
if sideLength >= 0:
volume = sideLength ** 3
else :
volume = 0
return volume
def cubeVolume(sideLength) :
if sideLength >= 0 :
return sideLength ** 3
# Error—no return value if sideLength < 0
Definition
def boxString(contents) : Call
n = len(contents) : ...
print("-" * (n + 2)) boxString("Hello")
print("!" + contents + "!") ...
print("-" * (n + 2))
return
Result
def boxString(contents) :
n = len(contents)
if n == 0 :
return # Terminates immediately
print("-" * (n + 2))
print("!" + contents + "!")
print("-" * (n + 2))
▪ 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++)
def main() :
sum = 0
for i in range(11) : sum
square = i * i i
sum = sum + square
print(square, sum)
square
def main():
sideLength = 10
result = cubeVolume()
print(result)
def cubeVolume():
return sideLength * sideLength * sideLength # ERROR
def square(n):
result = n * n result
return result
def main():
result = square(3) + square(4) result
print(result)
def withdraw(amount) :
# This function intends to access the
# global ‘balance’ variable
global balance
if balance >= amount :
balance = balance - amount
▪ Then keep breaking down the simpler tasks into even simpler
ones, until you are left with tasks that you know how to solve