Possible Duplicate:
Python variable scope question
Python nested function scopes
I'm confused about the following piece of code
def func():
a=10
def func2():
print a
a=20
func2()
print a
func()
In python 2.7, when running the above code, python will give an error, UnboundLocalError
, complaining in func2
, when print a
, 'a' is referenced before assignment
However, if I comment a=20
in func2
, everything goes well. Python will print two lines of 10; i.e, the following code is correct.
def func():
a=10
def func2():
print a
func2()
print a
func()
Why? Since in other languages, like c/c++
{
a=10
{
cout<<a<<endl //will give 10
a=20 //here is another a
cout<<a<<endl //here will give 20
}
}
local and outer variables can be distinguished very clearly.