In python, I can write :
def func():
x = 1
print x
x+=1
def _func():
print x
return _func
test = func()
test()
when I run it, the output is :
1
2
As _func has access to the "x" variable defined in func. Right...
But if I do :
def func():
x = 1
print x
def _func():
x+=1
print x
return _func
test = func()
test()
Then I got an error message : UnboundLocalError: local variable 'x' referenced before assignment
In this case, it seems that _func cannot "see" the "x" variable
The question is: Why does print x in the first example "see" the "x" variable, whereas the mathematical operator x+=1 throws an exception?
I don't understand why...
Check this answer : https://stackoverflow.com/a/293097/1741450
Variables in scopes other than the local function's variables can be accessed, but can't be rebound to new parameters without further syntax. Instead, assignment will create a new local variable instead of affecting the variable in the parent scope. For example:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With