Another For Loop
How about doing the same calculations for a range of values? Say you want to know the cost of a car for a range of gas prices. You can use a list to store the values and the for instruction to loop over the list
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 gallon_price_list = [2.20, 2.25, 2.30, 2.35, 2.40, 2.45] # the for instruction tells the computer to "loop" through # all indented lines below it for each value in a list for gallon_price in gallon_price_list: cost = gallon_price / mpg print 'When the gallon price is US$', gallon_price, print "the cost is US$", cost, "per mile" print
I saved it as mileage_loop.py
[cpn@dkt my_programs]$ python mileage_loop.py This program calculates a car mileage and its cost for a price range How many miles were measured ? 234.2 How many gallons of gas were consumed ? 9.3 mileage is 25.1827956989 miles per gallon when the gallon price is US$ 2.2 the cost is US$ 0.0873612297182 per mile when the gallon price is US$ 2.25 the cost is US$ 0.0893467122118 per mile when the gallon price is US$ 2.3 the cost is US$ 0.0913321947054 per mile when the gallon price is US$ 2.35 the cost is US$ 0.093317677199 per mile when the gallon price is US$ 2.4 the cost is US$ 0.0953031596926 per mile when the gallon price is US$ 2.45 the cost is US$ 0.0972886421862 per mile
The for instruction tells the computer to repeat all the indented lines below it for each value in a list of values. The indentation can be one, two or as many spaces as you like, but must be the same on all lines to be "looped".