On 10/19/13 8:23 AM, Scott Novinger wrote:
Hello.

I've written a program for my kids to calculate arc length.  I want to include 
some error testing for value types entered that are something other than 
integer values.

My goal is to make sure that the value entered for the radius is an integer 
value.

How could I rewrite this code to make sure I accomplish my goal of getting an 
integer value entered?  I know the construct is not correct.  I'm just learning 
how to program.

     # 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.

Scott
Hi Scott, welcome!

This line doesn't do what you want:

    if type(radius) != type(int):

for a few reasons: First, radius is the result of input(), so it is always a string, never an int. Second, "int" itself is already a type, so type(int) is actually "class" (or something like it), not "int".

What you want is to know whether the string inputted can be properly converted to an int. In Python, the way to do that is to try converting it, and be prepared for it to fail:

    try:
        radius = int(radius)
    except ValueError:
        print('You must enter an integer value.')

--Ned.
--
https://mail.python.org/mailman/listinfo/python-list

Reply via email to