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.

UnboundLocalError in Python

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.

Output of the solution to UnboundLocalError in Python

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.


Further Reading

  1. Why map entries are unddressable in Golang?
  2. [SOLVED] psql: FATAL database 'root' does not exist error
  3. What is Atatus APM and its Benefits?

Monitor your software stack for free with Atatus.

Start your free trial
OR
Request a Demo

Free 14-day trial. No credit card required. Cancel anytime.

Ready to see actionable data?

Avail Atatus features for 14 days free-trial. No credit card required. Instant set-up.