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
The idea behind
try–exceptis that you don’t check all the necessary conditions beforehand. In your case you don’t need to check for types insidetry. Because of theifstatement the exception will not be raised when it should.Also, you should definitely use
raw_input()on Python 2 and keep in mind that it always returns astr. What can differ is the result ofint(enterAge):This is what you need to try in the
tryblock and catch theValueError.Edit: Apparently I need to clarify the answer a little, so I’ll show how in my opinion the code should look: