What is it For?
The for statement will loop through a given list (or any sequence).
This program will show all models in a model list:
model_list = [('BMW Z4', 8.7), ('Audi TT', 8.6), ('Mercedez CLK350', 8.8)] print for model in model_list: print model printThis list is made of pairs or tuples of values. The first item in each tuple is the model name and the second is the acceleration times in seconds from 0 to 60 mph.
[cpn@dkt my_programs]$ python whatfor.py
('BMW Z4', 8.6999999999999993)
('Audi TT', 8.5999999999999996)
('Mercedez CLK350', 8.8000000000000007)But we can do better than that. We can show both model name and model accelaration as distinct values. The first item in a tuple has the 0 index and the second item has the 1 index:
model_list = [('BMW Z4', 8.7), ('Audi TT', 8.6), ('Mercedez CLK350', 8.8)] print for model in model_list: print 'The', model[0], 'acceleration is', model[1] printNow we have a nice output:
[cpn@dkt my_programs]$ python whatfor_better.py The BMW Z4 acceleration is 8.7 The Audi TT acceleration is 8.6 The Mercedez CLK350 acceleration is 8.8