please help explain this result
Yingjie Lan
lanyjie at yahoo.com
Sun Oct 17 06:58:21 EDT 2010
Hi,
I played with an example related to namespaces/scoping.
The result is a little confusing:
>>> a=1
>>> def f():
a = a + 1
return a
>>> f()
I suppose I will get 2 ( 'a' is redefined as a local variable, whose value is obtained by the value of the global variable 'a' plus 1). But this is what I got:
>>> a=1
>>> def f():
a = a + 1
return a
>>> f()
Traceback (most recent call last):
File "<pyshell#39>", line 1, in <module>
f()
File "<pyshell#38>", line 2, in f
a = a + 1
UnboundLocalError: local variable 'a' referenced before assignment
I'm not sure how to explain this? Thanks!
Yingjie
More information about the Python-list
mailing list