Tuesday, 15 January 2013

Python Language Lesson: for loop


Python Language Lesson: for loop

The for loop goes through the items of a list. In the example below,
we define a list of foods. Then we loop through the food items one by
one, printing each of them to the screen.
foods = [u"cheese", u"sausage", u"milk", u"banana", u"bread"]
for x in foods:
print x
This almost reads like English: ‘For x (every element) in (the list of)
foods, print (the name of) x’. When executing this for loop, the resulting
screen shows ‘cheese’, ‘sausage’, ‘milk’, ‘banana’ and ‘bread’, one item
per line.
If you want to loop over a range of numbers, you can use a special
range() function. This function produces a list of integers, from 0 to
the given maximum value.

for i in range(10):
print i
This prints out the numbers from 0 to 9.





No comments:

Post a Comment