+ 1
Can anyone tell why `x=x` is producing "UnboundLocalError: local variable 'x' referenced before assignment"?
3 Respuestas
+ 4
My interpretation is something like this:
Only if there's no local variable with the name, the function reads outwards to global.
The moment you write x = ..., you're telling Python you're going to define a local x. So the door to the outside world is closed.
So then when you add the x, x tries to refer to the local x, although you haven't defined it yet.
+ 1
The references are mangled up.
It will work like this:
x = 5
def foo(x):
x = x
print(x)
foo(x)
Because what happens here is actually:
x = 5
def foo(n):
d = n
print(d)
foo(x)