
42
|
Python Pocket Reference
The for Statement
for target in sequence:
suite
[else:
suite]
The for loop is a sequence iteration that assigns items in
sequence to target and runs the first suite for each. The for
statement runs the else suite if the loop exits without hitting
a
break statement. target can be anything that can appear on
the left side of an
= assignment statement (e.g., for (x, y) in
tuplelist:
).
In Version 2.2, this works by first trying to obtain an iterator
object with
iter(sequence) and then calling that object’s
next() method repeatedly until StopIteration is raised (see
the section “The yield Statement,” later in this book). In ear-
lier versions, or if no iterator object can be obtained (e.g., no
__iter__ method is defined), this works instead by repeat-
edly indexing
sequence at successively higher offsets until an
IndexError is raised.
The pass Statement
pass
This is a do-nothing placeholder statement, and is used when
syntactically necessary.
The break Statement
break
This immediately exits the closest enclosing while or for
loop statement, skipping its associated else (if any).