The following code gives the error
UnboundLocalError: local variable 'Var1' referenced before assignment:
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") Var1 =- 1 function()
How can I fix this? Thanks for any help!
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)
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
+= 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:
global Var1, Var2
inside the top of your function. This will tell Python that you don't intend to define a
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.