The While Loop

The while loop, as the name says, loops while a condition is true. In this case the condition is the gas price.

print
print "This program calculates a car mileage"
print "and its cost for a price range"
print

distance = float(raw_input("How many miles were measured ? "))
print
consumed = float(raw_input("How many gallons of gas were consumed ? "))

mpg = distance / consumed

print
print "mileage is", mpg, "miles per gallon"
print

# the while instruction tells the computer to "loop" through
# all indented lines below it "while" something is true
#
# in this case it will loop while the gallon price is lower then US$ 2.49

gallon_price = 2.20

while gallon_price < 2.49:
   cost = gallon_price / mpg
   print 'When the gallon price is US$', gallon_price,
   print "the cost is US$", cost, "per mile"

   # here we raise the gallon price
   gallon_price = gallon_price + 0.05

print

The gallon_price will first enter the loop with the value of 2.20 and at the end of each interaction (the last line in the loop) it will be raised by 0.05. Then the while will test if is it lower than 2.49. If it is the loop will be repeated.

The for loop is better to loop over a list and the while loop is better when you don't have or can't create a list.

[cpn@dkt my_programs]$ python mileage_while.py

This program calculates a car mileage
and its cost for a price range

How many miles were measured ? 285.3

How many gallons of gas were consumed ? 11.5

mileage is 24.8086956522 miles per gallon

When the gallon price is US$ 2.2 the cost is US$ 0.0886785839467 per mile
When the gallon price is US$ 2.25 the cost is US$ 0.0906940063091 per mile
When the gallon price is US$ 2.3 the cost is US$ 0.0927094286716 per mile
When the gallon price is US$ 2.35 the cost is US$ 0.094724851034 per mile
When the gallon price is US$ 2.4 the cost is US$ 0.0967402733964 per mile
When the gallon price is US$ 2.45 the cost is US$ 0.0987556957589 per mile

computer programming degree learning course tutorial