Вопрос

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-except is that you don't check all the necessary conditions beforehand. In your case you don't need to check for types inside try. Because of the if statement 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 a str. What can differ is the result of int(enterAge):

In [1]: int('4')
Out[1]: 4

In [2]: int('4f')
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
/home/lev/<ipython-input-2-523c771e7a8e> in <module>()
----> 1 int('4f')

ValueError: invalid literal for int() with base 10: '4f'

This is what you need to try in the try block and catch the ValueError.

Edit: Apparently I need to clarify the answer a little, so I'll show how in my opinion the code should look:

age = 0
while True:
    enterAge = raw_input('Enter your age as an integer: ')
    try:
        age += int(enterAge)
        print age, 'is old!'

    except ValueError:
        print "You didn't enter an integer"
        break
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top