0

UnboundLocalError: local variable 'text' referenced before assignment

Hi, I'm getting this error 'UnboundLocalError: local variable 'text' referenced before assignment'. How do you fix this?


Here is my Code:

even = None
def is_even(num):
    if num % 2 == 0:
        even = True
        return even
    elif num % 2 != 0:
        even = False
        return even

def lastmes():
    if even == True:
        text = "The last value of even is True"
    elif even == False:
        text = "The last value of even is False"
    return text

print(lastmes())
print(is_even(51))

Here is my error message:

Traceback (most recent call last):
  File "main.py", line 17, in <module>
    print(lastmes())
  File "main.py", line 15, in lastmes
    return text
UnboundLocalError: local variable 'text' referenced before assignment
Sara Simon
  • 33
  • 1
  • 3
  • 11
  • 1
    `even` is None. In `lastmes` both if-conditions are unsatisfied. Therefore `text` does not get set to anything. So trying to return it causes an exception. – khelwood Jul 01 '20 at 01:46
  • The value for even is None when you are running the code. That's why the program is not going into any of the definitions of text. So effectively you are returning a variable which does not exist. – Knl_Kolhe Jul 01 '20 at 01:46

2 Answers2

2

You should do 3 things.

First, make even variable inside the is_even function global. You are just creating another local variable and setting it's value which wont change the even you created outside the function.

def is_even(num):
    global even #Here
    if num % 2 == 0:
        even = True
        return even
    elif num % 2 != 0: #You should change this to just an else but this works too
        even = False
        return even

Second, change the elif in your lastmes function to else. If you plan on using elif and want to consider a possibility for even to be None, then you should add another else to deal with the None possibility.

def lastmes():
    if even == True:
        text = "The last value of even is True"
    else:
        text = "The last value of even is False"
    return text

Third, call is_even before lastmes so that the values are calculated, before checking them and displaying the messages.

print(is_even(50))
print(lastmes())
Ghost
  • 735
  • 5
  • 16
1

If even is neither True nor False, then text is never defined. even is set to None at the beginning of your program.

kindall
  • 178,883
  • 35
  • 278
  • 309