Python for Developers

First Edition

Chapter 4: Loops


Loops are repetition structures, generally used to process data collections, such as lines of a file or records of a database that must be processed by the same code block.

For

It is the repetition structure most often used in Python. The statement accepts not only static sequences, but also sequences generated by iterators. Iterators are structures that allow iterations, i.e. access to items of a collection of elements, sequentially.

Loop Example

During the execution of a for loop, the reference points to an element in the sequence. At each iteration, the reference is updated, in order for the for code block to process the corresponding element.

The clause break stops the loop and continue passes it to the next iteration. The code inside the else is executed at the end of the loop, except if the loop has been interrupted by break.

Syntax:

for <reference> in <sequence>:
    <code block>
    continue
    break
else:
    <code block>

Example:

In [1]:
# Sum 0 to 99
s = 0
for x in range(1, 100):
    s = s + x
print s
4950

The function range(m, n, p), is very useful in loops, as it returns a list of integers starting at m through smaller than n in steps of length p, which can be used as the order for the loop.

While

Executes a block of code in response to a condition.

Syntax:

while <condition>:
    <code block>
    continue
    break
else:
    <code block>

The code block inside the while loop is repeated while the loop condition is evaluated as true.

Example:

In [2]:
# Sum 0 to 99
s = 0
x = 1

while x < 100:
    s = s + x
    x = x + 1
print s
4950

The while loop is appropriate when there is no way to determine how many iterations will occur and there is a sequence to follow.

In [1]:
 
Out[1]: