[Tutor] Just started Python

Johnson Tran aznjonn at me.com
Wed Apr 27 14:32:31 CEST 2011


Hi All,

I am a complete beginner so my question will probably be pretty noob but:

I started out with a short program below and I thought it was working although I cannot seem to figure out how to use the except ValueError so that when the user puts an invalid answer the program does not read with an error. Although according to the error message, it seems to be saying that my line 4 "number1 = float (number_string1)" is incorrect. Thanks in advance for any advice.

Cheers,

Noob

Program:::
model=raw_input("What kind of car do you drive?")
number_string1=raw_input("How many gallons have you driven?")
number1 = float (number_string1)
number_string2=raw_input("How many miles have you driven?")
number2 = float (number_string2)


try:
    model=float(model)
except ValueError:
    pass
print "Your average number of miles to gallons is",
print number1 / number2
What kind of car do you drive?firebird
How many gallons have you driven?test


Output of Program::
T>>> ================================ RESTART ================================
>>> 
What kind of car do you drive?firebird
How many gallons have you driven?30
How many miles have you driven?60
Your average number of miles to gallons is 0.5
>>> ================================ RESTART ================================
>>> 
What kind of car do you drive?firebird
How many gallons have you driven?test

Traceback (most recent call last):
  File "/Users/JT/Desktop/test", line 4, in <module>
    number1 = float (number_string1)
ValueError: invalid literal for float(): test


More information about the Tutor mailing list