February 2006
Intermediate to advanced
648 pages
14h 53m
English
You implement loops using the for and while statements. For example:
while expression:
statements
for i in s:
statementsThe while statement executes statements until the associated expression evaluates to false. The for statement iterates over all the elements of s until no more elements are available. The for statement works with any object that supports iteration. This obviously includes the built-in sequence types such as lists, tuples, and strings, but also any object that implements the iterator protocol.
An object, s, supports iteration if it can be used with the following code, which mirrors the implementation of the for statement:
it = s.__iter__() # Get an iterator for s while 1: try: i = it.next() # Get next item ...