3.6.1 An example of a for loop

In programming a loop is a statement or block of statements that is executed repeatedly. for loops are used to do something a fixed number of times (where the number is known at the start of the loop). Here is an example:

      sumsquares = 0    # sumsquares must have a value because we increment
                        # it later.
      for i in [0, 1, 2, 3, 4, 5]:
          print "i now equal to:", i
          sumsquares = sumsquares + i**2    # sumsquares incremented here
          print "sum of squares now equal to:", sumsquares
          print "------"
      print "Done."

The indentation of this program is essential. Copy it into an empty module. IDLE will try and help you with the indentation but if it doesn't get it right use the TAB key3.6. Don't forget the colon at the end of the for line. The role of indentation is explained below but first let us consider the for loop. Try and work out what a for loop does from the program's output.

The for loop can actually be considered as a foreach loop: ``For each thing in the list that follows, execute some statements''. Remember a list is enclosed in square brackets. On each iteration of the loop, the next item in the list is assigned to i. That is to say, the first time around, i = 0, the second time i = 1, etc.

Indentation is an intrinsic part of Python's syntax. In most languages indentation is voluntary and a matter of personal taste. This is not the case in Python. The indented statements that follow the for line are called a nested block. Python understands the nested block to be the section of code to be repeated by the for loop.

Note that the print "Done." statement is not indented. This means it will not be repeated each time the nested block is. The blank line after the nested block is not strictly necessary, but is encouraged as it aids readability.

The editor and interactive interpreter will try and indent for you. If you are using the interpreter it will keep giving you indented lines until you leave an empty line. When you do this, the condition will be tested and if appropriate the nested block will be executed.


... key3.6
You can also use any number of spaces, as long as the number is consistent.