+ 1

Can anyone tell why `x=x` is producing "UnboundLocalError: local variable 'x' referenced before assignment"?

https://code.sololearn.com/cta3wEA4qsKE/?ref=app

24th Jun 2020, 7:14 AM
Bhanu Pratap Singh Bais
Bhanu Pratap Singh Bais - avatar
2 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.
24th Jun 2020, 7:23 AM
HonFu
HonFu - avatar
+ 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)
24th Jun 2020, 3:06 PM
loeckchen[INACTIVE]