0

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

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

5 Comments

"Because of the if statement the exception will not be raised when it should." I disagree based on the below code, on orange juice the exception is raised fridge = {'eggs': 8, 'cheese': 12, 'butter': 4, 'milk': 17} try: if fridge['milk'] > 0: print 'Drink some milk' except KeyError as error: print 'There is no %s' % error try: if fridge['orange juice'] > 0: print 'Drink some orange juice' except KeyError as error: print 'There is no %s' % error Why can't I get the linebreaks to work?
@MichaelSwartz In this case the exception is caused when the condition is evaluated inside if: fridge['orange juice'] > 0 itself causes the exception, so this is the correct use of try. But in the question the possible problem is the wrong type, so the try is there to account for it, but if checks the same thing. type(enterAge) is IntType can't produce an exception, that's the difference. And yeah, you can't have linebreaks in comments. Sometimes it's frustrating. You can edit your question in response to answers and comments, though.
So my code is wrong because something like ("x" * 100) is ("x" * 100) is False but ("x" * 100) == ("x" * 100) is True because is tests for identity and not equality?
Not sure about the use of is in the context (it may work, as a simple test shows), but my point is that your code is wrong that you put an exception-safe piece of code in a try block. You made it safe by using if. You should either use if or try in the code shown in your question. Another mistake you made, as I mentioned before, is that the user input returned by raw_input will always be str unless you explicitly convert it, so you need to account for that.
@MichaelSwartz I edited the answer, hope it helps. Feel free to ask.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.