Reputation: 405
I am trying to find a reason to this Error. The Code Is
def x():
if b == 1:
a = a + 4
print(a)
a = 5
b = 1
x()
The second time my variable a
is used : a = a + 4
, an error occur.
I am developing a program which mainly uses this type of assignments.
Upvotes: 3
Views: 15657
Reputation: 10782
The assignment a = a + 4
tells the interpreter to use a local version of a
instead of the global reference.
Now in the assignment a = a + 4
, when the interpreter is looking up the value of the local variable a
, the interpreter finds the variable to be undefined and will yield UnboundLocalError: local variable 'a' referenced before assignment
.
You can change this behavior by using the global
keyword:
def x():
global a
if b == 1:
a = a + 4
print(a)
return
a = 5
b = 1
x()
Q: Hold on, why isn't the interpreter complaining about b
?
A: Because you're not assigning anything to b within the function, thus the interpreter will use the variable b
from the global scope.
However, global variables are not needed for this case. A more elegant version that avoids global variables would be:
def x(a, b):
if b == 1:
a = a + 4
return a
print( x(5, 1) )
Note that this function behaves slightly differently. Your original function did not return anything, while my reworked version of x
will always return the value of a
, either modified or unmodified, depending on the value of b
.
This has the advantage that you can work with the returned value and you can move the print()
out of the function.
Upvotes: 14