5 Control Constructs

Python has if, for, and while control statements. The for statement is different than that in most other languages; it is more like the foreach loop in csh. It takes the following form:

for item in itemlist:
  print item

The loop body is executed with a new value for the variable item for each iteration. The values are taken from a sequence-like object (such as a string, list, or tuple ... but other possibilities exist), and item is set to each of the values in the sequence.

Note the colon after the statement - all statements that control the execution of a following block of statements (including for, if, while, etc.) end with a colon.

To get the common loop over consecutive integers, use the built-in range function:

for i in range(100): print i

range(100) constructs a list of values from 0 to 99 (yes, 99!) and the for loop repeats 100 times with values of i starting at 0 and ending at 99. The argument to range is the number of elements in the returned list, not the maximum value. There are additional arguments to range if you want a loop that starts at a value other than zero or that increments by a value other than 1.

Questions or comments? Contact help@stsci.edu
Documented updated on 2004 Jun 1