Use Python's “
to do some repetitive operation for each member of a
sequence. Here is the general form:
can be any expression that evaluates to a sequence
value, such as a list or tuple. The
range() function is often used here to
generate a sequence of integers.
For each value in the
in turn, the
to that value, and the
As with the
if statement, the block
consists of one or more statements, indented the same
amount relative to the
This example prints the cubes of all numbers from 1 through 5.
>>> for n in range(1,6): ... print "The cube of %d is %d." % (n, n**3) ... The cube of 1 is 1. The cube of 2 is 8. The cube of 3 is 27. The cube of 4 is 64. The cube of 5 is 125.
You may put the body of the loop—that is, the
statements that will be executed once for each item in
the sequence—on the same line as the “
for” if you like. If there are multiple
statements in the body, separate them with semicolons.
>>> for n in range(1,6): print "%d**3=%d" % (n, n**3), ... 1**3=1 2**3=8 3**3=27 4**3=64 5**3=125
Here is an another example. In this case, the sequence is a specific list.
>>> for s in ['a', 'e', 'i', 'o', 'u']: ... word = "st" + s + "ck" ... print "Pick up the", word ... Pick up the stack Pick up the steck Pick up the stick Pick up the stock Pick up the stuck