Yet Another
Now we want to show how fast each car model accelerates from 0 to 60 mph.
We build a list of pairs. Each pair contains the car model and the corresponding number of seconds each model takes to go from 0 to 60 mph.>
The for loop prints one line for each pair model-acceleration:
print print 'How many seconds each model takes to go from 0 to 60 mph' print # build a list of pairs (model, acceleration) model_list = [('BMW Z4', 8.7), ('Audi TT', 8.6) , ('Mercedez CLK350', 8.8)] # print for each model, its corresponding acceleration # for model, acceleration in model_list: print 'The', model, 'acceleration is', acceleration, 'seconds' print
Notice how the pairs are unpacked by the for instruction.
[cpn@dkt my_programs]$ python acceleration_loop.py How many seconds each model takes to go from 0 to 60 mph The BMW Z4 acceleration is 8.7 seconds The Audi TT acceleration is 8.6 seconds The Mercedez CLK350 acceleration is 8.8 seconds
Proposed Exercise
Change the program above to also show each model's price.