



Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!




Today ...
Homework
Variables defined inside a function are local to the function
For example
def add_and_print(x, y): sum = x + y print(sum)
Q: What does this function do?
arg1 = 3 arg2 = 4 add_and_print(arg1, arg2) 7
When a function terminates, local variables are destroyed
print(sum) NameError: name ’sum’ is not defined
The same is true for function parameters!
What about now?
sum = 10 x = 5 y = 4 z = 1 def add_and_print(x, y): sum = x + y + z print(sum) add_and_print(3, 4) print(sum, x, y, z, sep=", ")
Q: What is printed by the add and print function call?
8
Q: What is printed by the last statement?
10, 5, 4, 1
Equivalent to:
sum = 10 x = 5 y = 4 z = 1 def add_and_print(x0, y0): sum = x0 + y0 + z print(sum) add_and_print(3, 4) print(sum, x, y, z, sep=", ")
What about this one?
sum = 10 x = 5 y = 4 z = 1 def add_and_print(x, y): sum = x + y + z print(sum) z = 2 add_and_print(3, 4) print(sum, x, y, z, sep=", ")
UnboundLocalError: local variable ’z’ referenced before assignment