Play it again, Sam

It is not good to have to restart the program for every mileage that we want to calculate the cost. This program will keep asking a new mileage until the user enters 0, thanks to the while True condition:

print

# as the condition for this while loop is always true
# it will execute forever unless...
#
while True:

    mpg = float(raw_input("What is the mileage? Enter 0 to stop: "))
    print

    # here is the unless part.
    # if the user enters the value 0 the while loop will be broken
    #
    # the comparison operator is two equal signs "=="
    # not only one "="
    #
    if mpg == 0:

        # the if block also has to be indented

        print 'The end...'
        print

        # the break instruction breaks the loop,
        # be it a while loop or a for loop
        #
        break

    # here in instead of building a list ourselves
    # we let the range function build it for us
    #
    gallon_price_list = range(220, 250, 5)

    for gallon_price in gallon_price_list:

        cost = gallon_price / mpg
        print 'gallon price in US$', gallon_price / 100.0,
        print "cost in US$", cost, "per hundred miles"

    print


[cpn@dkt my_programs]$ python mileage_again.py

What is the mileage? Enter 0 to stop: 22

gallon price in US$ 2.2 cost in US$ 10.0 per hundred miles
gallon price in US$ 2.25 cost in US$ 10.2272727273 per hundred miles
gallon price in US$ 2.3 cost in US$ 10.4545454545 per hundred miles
gallon price in US$ 2.35 cost in US$ 10.6818181818 per hundred miles
gallon price in US$ 2.4 cost in US$ 10.9090909091 per hundred miles
gallon price in US$ 2.45 cost in US$ 11.1363636364 per hundred miles

What is the mileage? Enter 0 to stop: 27

gallon price in US$ 2.2 cost in US$ 8.14814814815 per hundred miles
gallon price in US$ 2.25 cost in US$ 8.33333333333 per hundred miles
gallon price in US$ 2.3 cost in US$ 8.51851851852 per hundred miles
gallon price in US$ 2.35 cost in US$ 8.7037037037 per hundred miles
gallon price in US$ 2.4 cost in US$ 8.88888888889 per hundred miles
gallon price in US$ 2.45 cost in US$ 9.07407407407 per hundred miles

What is the mileage? Enter 0 to stop: 0

The end...

[cpn@dkt my_programs]$

Proposed exercise

Break the while loop if the mileage is equal or lower than 0 or if the mileage is bigger than 100.

computer programming degree learning course tutorial