There are tow simple functions owning nested function, as follows:
def a():
abc = 1
def write():
print abc
write()
def b():
abc = 1
def write():
print abc
abc += 1
write()
The difference between these tow is just that I tried to change the value of the variable.
When I run a(),that's ok.
When I run b(),I get back the error "UnboundLocalError: local variable 'abc' referenced before assignment"
What is the reason?
The problem you're encountering is in the scope of variables. The nested functions in your program have their own local namespace/scope different from the outer function that calls them.
According to Python documentation
Meaning that if you instead try this:
your function
b
will run without errors. This also means that the value ofabc
will increase globally and become2
after callingwrite()
.If you don't declare your
abc
variable asglobal
, it will be read-only for the nested functionwrite()
.write()
won't be able to change it but it will be able to print it, or locally re-assign it. The following also works because it first reassigns the value ofabc
to another, local variable and then changes that variable,You can print local variables in a given scope using
print locals()
.