I have a function which works with integers. I have added code for exception handling if strings or floats are entered, however, Python keeps returning either nonsense or NameError
. At this point I have tried a loop which keeps asking until an integer is entered and a try
and except
. Nothing works.
Here's the code:
def threes(num):
"""isNotCorrect = True
while isNotCorrect:
print(type(num))
if type(num) is not int:
print("Sorry, you need to enter a whole number to play Threes.")
else:
print('X')
isNotCorrect = False"""
try:
while num > 1:
if num % 3 == 0:
num = num/3
else:
if ((num + 1) % 3 == 0):
num = (num + 1)/3
else:
num = (num - 1)/3
print(num)
except NameError:
print("Invalid number. Please enter a valid number.")
Entering a whole number(the intended input) executes the code fine, but everything else leads to a name error like this, where the input is threes(bob)
. The top part is my attempt at a loop, which also failed and returned the same error;
Traceback (most recent call last):
File "<input>", line 1, in <module>
NameError: name 'bob' is not defined