UnboundLocalError: local variable

UnboundLocalError: local variable ‘is_prime’ referenced before assignment

In python UnboundLocalError: local variable ‘is_prime’ referenced before assignment we face this error message when we repeat the same code of line in the loop. We are human and we all do mistakes this is a very rare scenario if you face this error you mean you are a great programmer. To fix this error just remove the repeat code line in the loop, For more clarification see the below example.

Wrong Code

print("Welcome to Amol Blog Prime Number checker!")
n = int(input("Please Enter number:"))

def prime(number):
    for i in range(2, number):
        is_prime = True
    for i in range(2, number):
        if number % i == 0:
            is_prime = False
    if is_prime:
        print(f"Number {n} It's a prime number.")
    else:
        print(f"Number {n} It's not a prime number.")


prime(number = n)

Error Massage

Please Enter number:1
Traceback (most recent call last):
  File "/home/kali/python/webproject/simple_projects/prime_number/main.py", line 16, in <module>
    prime(number = n)
  File "/home/kali/python/webproject/simple_projects/prime_number/main.py", line 10, in prime
    if is_prime:
UnboundLocalError: local variable 'is_prime' referenced before assignment

Wrong code line

    for i in range(2, number):
        is_prime = True
    for i in range(2, number):

Correct code line

    is_prime = True
    for i in range(2, number):
  • Wrong action: we repeat this line 2 type for i in range(2, number).
  • Correct action: Remove 1 line and do the correct indentation.

Entire Correct Code line

print("Welcome to Amol Blog Prime Number checker!")
n = int(input("Please Enter number:"))

def prime(number):
    is_prime = True
    for i in range(2, number):
        if number % i == 0:
            is_prime = False
    if is_prime:
        print(f"Number {n} It's a prime number.")
    else:
        print(f"Number {n} It's not a prime number.")


prime(number = n)

What is UnboundLocalError: local variable referenced before assignment?

In python, we face this error message when we repeat the same code of line in the loop. We are human and we all do mistakes this is a very rare scenario.

How to fix UnboundLocalError: local variable referenced before assignment?

If you want to fix this error just remove the repeat code line in the loop, For more clarification see the above example.

For more information Visit YouTube Channel.

Scroll to Top
Top 7 Gaming Project In python Save ₹25,000 Laptop under ₹11,999 Top 7 Funny error in Python Unicodeescape Most dangerous error in Python Hero Electric Battery Price In 2023