Q:

while x is ValueError:

I currently have this code:
yon = raw_input("were you running in km y or n?: ")
if yon is "y":
    kilnumber = raw_input("how many kilometers?: ")
    milnumber = 0
    try:
        float(kilnumber)
    except:
        print "You must enter a number"
        exit()

I was hoping to make it simpler by adding a while loop to re-ask kilnumber if the user enters an illegal response. I was hoping for something like this:
yon = raw_input("were you running in km y or n?: ")
if yon is 'y':
    kilnumber = raw_input("how many kilometers?: ")
    milnumber = 0
    while float(kilnumber) is ValueError:
        print "You must enter a number"
        kilnumber = raw_input("how many kilometers?: ")

This code doesn't work because it sends an error message before evaluating the while loop. Solution?

A:

float(kilnumber) will never evaluate to ValueError. Rather, it may throw a ValueError. You need to catch it:
while True:
    try:
        float(kilnumber)
    except ValueError:
        # Not a valid number
        print "You must enter a number"
        kilnumber = raw_input("how many kilometers?: ")
    else:
        # No error; stop the loop
        break

See the tutorial for more on exceptions and errors.

