[Tutor] learning nested functions
Tim Hanson
tjhanson at yahoo.com
Mon Jul 8 08:26:25 CEST 2013
In the first Lutz book, I am learning about nested functions.
Here's the book's example demonstrating global scope:
>>> def f1():
x=88
def f2():
print(x)
f2()
>>> f1()
88
No problem so far. I made a change and ran it again:
>>> def f1():
x=88
def f2():
print(x)
x=99
print(x)
f2()
>>> f1()
Traceback (most recent call last):
File "<pyshell#11>", line 1, in <module>
f1()
File "<pyshell#10>", line 7, in f1
f2()
File "<pyshell#10>", line 4, in f2
print(x)
UnboundLocalError: local variable 'x' referenced before assignment
This doesn't work. To my mind,in f2() I first print(x) then assign a variable
with the same name in the local scope, then print the changed x. Why doesn't
this work?
More information about the Tutor
mailing list