[Tutor] Just started Python

Noah Hall enalicho at gmail.com
Wed Apr 27 16:20:21 CEST 2011


On Wed, Apr 27, 2011 at 1:32 PM, Johnson Tran <aznjonn at me.com> wrote:
> 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)

There's no validation for the variables when you try to convert them
(see bottom)

> number_string2=raw_input("How many miles have you driven?")
> number2 = float (number_string2)
>
>
> try:
>    model=float(model)
> except ValueError:
>    pass

Well, I'm not sure why you're trying to do this. You've obviously come
up with the error of it always raising exception due to the fact that
model is always going to be a string, so you've come up with a way to
avoid that. Why on earth would you want to always try to convert
something to float that you want as a string anyway? Think about it,
and see if you can figure out why this bit is all wrong.

> 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?30
> How many miles have you driven?60
> Your average number of miles to gallons is 0.5

> 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

Your problem is that you're passing the string 'test' to the float
function. The string 'test' is not a valid value for the function
float, so it raises a ValueError - the Value that you're passing to
the function is wrong. In order to get around this, you'll want to
make sure that whatever you pass to the float function is a valid
value.


More information about the Tutor mailing list