Loops are an important control structure

something about python loops

For Loop

The iteration variable i is assigned to the list of given values.

for i in range(10): print i

It is resilient against modifications during a single iteration:

for k in range(-5,5): print "k=", k k = k + 2 * k + 1 print "modified k=", k

While Loop

j = 5 while j >= 0: print j j -= 1

Iteration Loop

who = ["boy", "girl", "teacher", "banana"] for name in who: print name.title()

The iterator enumerate yields tuples of (<index number>, element). The <index number> zero and increments by 1 for each element in the list

cities = ["peking", "paris", "new york", "casablanca"] for index, city in enumerate(cities): print index, city

For-else construction

This is useful to iterate until a condition is met.

for x in [2,5,7,11,15,23,31,97]: if x % 3 == 0: print x, "is divisible by 3" break else: print "no number was divisible by 3"

Task: Change the 15 to 17 in the example above and try again.

Source
Mentioned in
Control Structures
Outgoing
Indexing, Iterator, List