



Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
Lecture notes from cpsc 121 (fall 2012) discussing the concept of variable visibility and scope in python functions. It explains how variables defined inside a function are local and only exist within the function, and how function parameters are treated as local variables. It also covers the concept of global variables and the implications of reassigning global variables within a function.
Typology: Study notes
1 / 5
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