Spirits Spirits - 2 years ago 170
Python Question

Python function keeps returning NameError even with exception handling

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

Answer Source

NameError: name 'bob' is not defined means that you try to use a variable named bob but you didn't create it.
You have to define what is bob like that for exemple :
bob = 'a simple man' # bob is a string
or
bob = 4 # bob is an integer

Furthermore, I just want you to know that even if it works, try to avoid using try/except because this is quite slow when you have to enter in the except block.

If you want to check if your variable is an integer I recommend you using :

if isinstance(bob, int):
    # do something
else:
    # do something else

Where isinstance() is a built-in function.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download