[Tutor] Just started Python

Alan Gauld alan.gauld at btinternet.com
Thu Apr 28 00:13:37 CEST 2011


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

> Thanks for the reply Alan and Noah, I really appreciate
> the help. I am really trying to understand this although
> still cannot seem to grasp it all.

Lets step back a stage.

Do you understand what float() does?

> I have modified my program although now it seems
> to be giving me the wrong answer with the correct
> answer when I input any value.
>
> model=raw_input("What kind of car do you drive?")
> gallons=raw_input("How many gallons have you driven?")
> number1 = float (gallons)

This is taking the value typede by the user and trying
to convert it from a string to a floating point number - that is,
a decimal value

> miles=raw_input("How many miles have you driven?")
> number2 = float (miles)

Similarly this converts the input string to a decimal value,
if possible.

> try:
>   model=float(model)

But what is this doing?

It is trying to convert the model of car to a decimal value.
Unless trhe car is a Porche 911 or similar its unlikely
to succeed! If its a Toyota Prius it will fail with a ValueError
exception.

> except ValueError:
>   print "I cannot compute your total miles to gallon with those 
> values."

And therefore print this message

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

The second print needs to be inside the else too.

> What kind of car do you drive?fire
> How many gallons have you driven?10
> How many miles have you driven?5
> I cannot compute your total miles to gallon with those values.

Because it cannot convert 'fire' to a decimal value.

HTH,


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




More information about the Tutor mailing list