Docsity

Variable Visibility and Scope in Python Functions, Study notes of Computer Science

Partial preview of the text

Download Variable Visibility and Scope in Python Functions and more Study notes Computer Science in PDF only on Docsity!

Today ...

  • Functions (cont.)

Homework

  • HW 2 due
  • HW 3 out

Function Variable Visibility

Variables defined inside a function are local to the function

  • i.e., they only exist inside 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

  • If we try to print them, we’ll get an error ...

print(sum) NameError: name ’sum’ is not defined

The same is true for function parameters!

  • e.g., trying to print x gives the same error

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=", ")

  • here z is a “global variable” ... it is defined outside of the function
  • sum, x, and y are also global variables

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=", ")

  • This confuses Python!

UnboundLocalError: local variable ’z’ referenced before assignment

  • Python thinks z is local (because of the assignment) ...
  • But then is used before it is assigned a value