I have a problem that when i try to use a global variable inside a method, an error is produced ("local variable 'b' referenced before assignment"). Why is this not the case when the variable is an element of a list?
this works fine:
a = [1]
def a_add():
a[0] += 1
a_add()
print(a)
but this doesn't:
b = 1
def b_add():
b += 1
b_add()
print(b)
The official FAQ page has detailed explanation for this error:
>>> x = 10
>>> def foo():
... print(x)
... x += 1
>>> foo()
Traceback (most recent call last):
...
UnboundLocalError: local variable 'x' referenced before assignment
This is because when you make an assignment to a variable in a scope, that variable becomes local to that scope and shadows any similarly named variable in the outer scope. Since the last statement in foo assigns a new value to x, the compiler recognizes it as a local variable. Consequently when the earlier print(x) attempts to print the uninitialized local variable and an error results.
And for code:
a = [1]
def a_add():
a[0] += 1
a_add()
print(a)
It just reads value from and assigns value to the first slot of the global array, so there's no problem.
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