Error Testing

Chris Angelico rosuav at gmail.com
Sat Oct 19 09:01:28 EDT 2013


On Sat, Oct 19, 2013 at 11:23 PM, Scott Novinger <scnovinger at gmail.com> wrote:
>     # Create the variable for radius, "radius".
>     print('Please enter the circle radius and press ENTER:')
>     radius = input()
>
>     # Check to make sure the entered value is an integer.
>     if type(radius) != type(int):
>         print('You must enter an integer value.')
>         print('Please enter the circle radius and press ENTER:')
>         radius = input()
>     else:
>         print('The radius you entered is: ' + radius)
>
>     radius = int(radius)
>
> Thanks for your help. I'm using Python v3.2 for windows.

In Python 3, the input() function always returns a string. Your type
check is never going to succeed. Also, you're not checking what you
think you're checking; you're actually looking to see if input()
returned a type, because the type of int is type:

>>> type(int)
<class 'type'>

You might want:

if type(radius) != int:

But that still won't work, because input() will always return a string:

>>> radius = input()
42
>>> type(radius)
<class 'str'>

You can try all these out in the interactive interpreter (you probably
have IDLE installed, which on Windows is rather nicer to work with
than the default interactive mode).

A better check would be to just try to turn the inputted value into an
integer, and fail if that doesn't work. Again, try this interactively:

>>> int("42")
42
>>> int("not an integer")
Traceback (most recent call last):
  File "<pyshell#58>", line 1, in <module>
    int("not an integer")
ValueError: invalid literal for int() with base 10: 'not an integer'

With a couple of quick checks, you can easily see what happens if the
conversion fails, and then you can deal with that failure. So
effectively, just drop the whole if: block, go straight to the "radius
= int(radius)" line, and deal with the error there.

ChrisA



More information about the Python-list mailing list