Next / Previous / Contents / TCC Help System / NM Tech homepage

6.4. The for statement: Looping

Use Python's “for” construct to do some repetitive operation for each member of a sequence. Here is the general form:

for variable in sequence:
    block
    ...

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