I have a global variable I called Y_VAL which is initialized to a value of 2.
I then have a function, called f() (for brevity), which uses Y_VAL.
def f():
y = Y_VAL
Y_VAL += 2
However, when trying to run my code, python gives the error message:
UnboundLocalError: local variable 'Y_VAL' referenced before assignment
If I remove the last line Y_VAL += 2
it works fine.
Why does python think that Y_VAL is a local variable?
You're missing the line global Y_VAL
inside the function.
When Y_VAL
occurs on the right-hand-side of an assignment, it's no problem because the local scope is searched first, then the global scope is searched. However, on the left-hand-side, you can only assign to a global that way when you've explicitly declared global Y_VAL
.
From the docs:
It would be impossible to assign to a global variable without global, although free variables may refer to globals without being declared global.
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