I'm experimenting with exception handling / error trapping and was wondering why the below code doesn't work. I'm using python 2.7. I understand the difference between input() and raw_input() and understand that raw_input() has been renamed to input() in Python 3.0. If I enter an integer then the code keeps looping until I enter a string. I get the below error message when entering a string. Is there a way around this or is this just one of those python quirks?
File "<some_directory_path_goes_here>", line 30, in <module>
enterAge = input('Enter your age as an integer: ')
File "<string>", line 1, in <module>
NameError: name '<user_entered_string_goes_here>' is not defined
In python 2.7 it would seem to me that the code should still work.
from types import IntType
age = 0
while True:
enterAge = input('Enter your age as an integer: ')
try:
if type(enterAge) is IntType:
num = enterAge
age = age + num
print str(age) + ' is old!'
except TypeError:
print 'You did\'t enter an integer'
break