[Tutor] Just started Python
Alan Gauld
alan.gauld at btinternet.com
Thu Apr 28 02:05:55 CEST 2011
"Johnson Tran" <aznjonn at me.com> wrote
> Okay so my final program is:
It works but you can improve it slightly with a simple change.
> model=raw_input("What kind of car do you drive?")
> gallons=raw_input("How many gallons have you driven?")
> miles=raw_input("How many miles have you driven?")
>
> try:
> number1 = float(gallons)
> number2 = float(miles)
Combine these two groups of lines so that you detect
the errors as soon as possible.:
try:
model=raw_input("What kind of car do you drive?")
gallons=raw_input("How many gallons have you driven?")
number1 = float(gallons)
miles=raw_input("How many miles have you driven?")
number2 = float(miles)
Now the user gets prompted as soon as they enter a wrong
number, they don't need to guess which one was wrong...
except ValueError:
print "That value is the wrong type, please use a number."
And so we can make the message more specific too.
> else:
> 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