[Tutor] Just started Python

Alan Gauld alan.gauld at btinternet.com
Wed Apr 27 19:02:17 CEST 2011


"Johnson Tran" <aznjonn at me.com> wrote

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

You have to replace the line that says 'pass' 
with code that does something to make the value 
correct. Asking the user to try again with a more 
sensible value would be a start.

> Although according to the error message, it 
> seems to be saying that my line 4 
> "number1 = float (number_string1)" is incorrect. 

Its not saying its incorrect, its saying thats where 
the ValueError occured. Which is true because you 
entered 'test' which cannot be converted to a 
float - its an invalid value.

> 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)

You will fin it easier if you use descriptive names for 
your variables.

gallons and miles 

would seem reasonable here...

> try:
>    model=float(model)
> except ValueError:
>    pass

This says if you get an error ignore it (ie pass).
But you don't want to ignore it, you want to get 
a valid value.

> print "Your average number of miles to gallons is",
> print number1 / number2

HTH,


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/




More information about the Tutor mailing list