How do you fix UnboundLocalError in Python?
Python is growing rapidly day by day and it is everywhere. Here we will discuss how to fix the UnboundLocalError in Python.
The Problem
num1 = 1
num2 = 0
def func():
if num2 == 0 and num1 > 0:
print("Result is 1")
elif num2 == 1 and num1 > 0:
print("Result is 2")
elif num1 < 1:
print("Result is 3")
num1 =- 1
func()
The following error occurs when compiling the code. Within this function, we have defined a global variable that appears within a loop.
The Solution
The above code can be modified to resolve this issue.
num1 = 1
num2 = 0
def func():
global num1
if num2 == 0 and num1 > 0:
print("Result is 1")
elif num2 == 1 and num1 > 0:
print("Result is 2")
elif num1 < 1:
print("Result is 3")
num1 =- 1
func()
Using this code, we will now achieve the desired results.
Reason
The error occurs when num1
is declared inside the function as num1=-1
because a local variable masks the global variable in the code.
Using global variables outside of the function may be confusing and cause problems. If you would like to incorporate this code, you could use the global num1
in the function.
By doing this, Python will know that you do not intend to define a variable with the names num1
or num2
within the function.