03.python.05.functions
03.python.05.functions
# acquire n
# acquire k
# check constraints and eventually repeat • abstract the
# compute factorial n functionality to
compute the
# compute factorial k factorial
# compute factorial (n-k) • re-use the
# compute result functionality easily
# display result
example
n = int(input())
while n < 0:
n = int(input())
k = int(input())
while k < 0 or n < k:
k = int(input())
fn = factorial(n)
fk = factorial(k)
fnk = factorial(n-k)
n = int(input())
k = int(input())
while not (n >= 0 and k >= 0 and n >= k):
n = int(input())
k = int(input())
def factorial(value):
if value >= 0:
res = 1
for i in range(2, value+1):
res = res * i
else:
res = -1 #a value that cannot be correct
return res
example
function: no argument, no result
example
function: no argument, a result
example
function: argument, a result
call
<name>(arg1, … argN)
arguments
10
inside sub 1
10
11
-----------
after sub 1
10
[1, 2, 3, 4, 5]
inside sub 2
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5, 100]
-----------
after sub 2
[1, 2, 3, 4, 5, 100]
scope
global local
STOP = 5 <statements>
def fact(val):
def checkinput(): f = 1
sel = int(input()) for i in range(2,val+1):
while sel != STOP: f = f * i
<statements> <statements>
for i in range(0,n):
print(i, fact(i))
global vs local
• if a variable is assigned
inside a def, it is local to
that function.
• if a variable is assigned
in an enclosing def, it is
nonlocal to nested
functions.
• if a variable is assigned
outside all defs, it is
global to the entire file.
global vs local: careful!
mylst = [1, 2, 3, 4] i = …
base = 1
def multiple(x): p, newl = multiple(base)
y = x*2
r = [x, y] p, newl
return y, r (2, [1, 2])
guidelines