Reputation: 31
How do you fix this error?
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
Upvotes: -1
Views: 4023
Reputation: 735
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())
Upvotes: 2
Reputation: 184465
If even
is neither True
nor False
, then text
is never defined. even
is set to None
at the beginning of your program.
Upvotes: 1