The Python "UnboundLocalError: Local variable referenced before assignment" occurs when we reference a local variable before assigning a value to it in a function. To solve the error, mark the variable as global in the function definition, e.g. global my_var .
UnboundLocalError can be solved by changing the scope of the variable which is complaining. You need to explicitly declare the variable global. Variable x's scope in function printx is global. You can verify the same by printing the value of x in terminal and it will be 6.
the Solution of local variable referenced before assignment Error in Python. We can declare the variable as global using the global keyword in Python. Once the variable is declared global, the program can access the variable within a function, and no error will occur.
The UnboundLocalError: local variable referenced before assignment error is raised when you try to assign a value to a local variable before it has been declared. You can solve this error by ensuring that a local variable is declared before you assign it a value.
This is because, even though Var1
exists, you're also using an assignment statement on the name Var1
inside of the function (Var1 -= 1
at the bottom line). Naturally, this creates a variable inside the function's scope called Var1
(truthfully, a -=
or +=
will only update (reassign) an existing variable, but for reasons unknown (likely consistency in this context), Python treats it as an assignment). The Python interpreter sees this at module load time and decides (correctly so) that the global scope's Var1
should not be used inside the local scope, which leads to a problem when you try to reference the variable before it is locally assigned.
Using global variables, outside of necessity, is usually frowned upon by Python developers, because it leads to confusing and problematic code. However, if you'd like to use them to accomplish what your code is implying, you can simply add, inside the top of your function:
global Var1, Var2
This will tell Python that you don't intend to define a Var1
or Var2
variable inside the function's local scope. The Python interpreter sees this at module load time and decides (correctly so) to look up any references to the aforementioned variables in the global scope.
nonlocal
statement - check that out as well.If you set the value of a variable inside the function, python understands it as creating a local variable with that name. This local variable masks the global variable.
In your case, Var1
is considered as a local variable, and it's used before being set, thus the error.
To solve this problem, you can explicitly say it's a global by putting global Var1
in you function.
Var1 = 1
Var2 = 0
def function():
global Var1
if Var2 == 0 and Var1 > 0:
print("Result One")
elif Var2 == 1 and Var1 > 0:
print("Result Two")
elif Var1 < 1:
print("Result Three")
Var1 =- 1
function()
You can fix this by passing parameters rather than relying on Globals
def function(Var1, Var2):
if Var2 == 0 and Var1 > 0:
print("Result One")
elif Var2 == 1 and Var1 > 0:
print("Result Two")
elif Var1 < 1:
print("Result Three")
return Var1 - 1
function(1, 1)
I don't like this behavior, but this is how Python works. The question has already been answered by others, but for completeness, let me point out that Python 2 has more such quirks.
def f(x):
return x
def main():
print f(3)
if (True):
print [f for f in [1, 2, 3]]
main()
Python 2.7.6 returns an error:
Traceback (most recent call last):
File "weird.py", line 9, in <module>
main()
File "weird.py", line 5, in main
print f(3)
UnboundLocalError: local variable 'f' referenced before assignment
Python sees the f
is used as a local variable in [f for f in [1, 2, 3]]
, and decides that it is also a local variable in f(3)
. You could add a global f
statement:
def f(x):
return x
def main():
global f
print f(3)
if (True):
print [f for f in [1, 2, 3]]
main()
It does work; however, f becomes 3 at the end... That is, print [f for f in [1, 2, 3]]
now changes the global variable f
to 3
, so it is not a function any more.
Fortunately, it works fine in Python3 after adding the parentheses to print
.
Why not simply return your calculated value and let the caller modify the global variable. It's not a good idea to manipulate a global variable within a function, as below:
Var1 = 1
Var2 = 0
def function():
if Var2 == 0 and Var1 > 0:
print("Result One")
elif Var2 == 1 and Var1 > 0:
print("Result Two")
elif Var1 < 1:
print("Result Three")
return Var1 - 1
Var1 = function()
or even make local copies of the global variables and work with them and return the results which the caller can then assign appropriately
def function():
v1, v2 = Var1, Var2
# calculate using the local variables v1 & v2
return v1 - 1
Var1 = function()
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