[Tutor] FOR loops

alan.gauld@bt.com alan.gauld@bt.com
Tue, 5 Oct 1999 17:54:37 +0100

> message comes in, I got to the part that introduces FOR loops
> the book doesn't explain the concept very well and I don't understand
> how to use FOR loops in my programs.Could anyone explain what 
> FOR loops
> do and how to implement them in my programming?? I would really
> appreciate it.

Shameless plug follows:

My programming tutor has this to say:
(context is building a 'multiplication table' generator)

FOR Loops

What we are going to do is get the programming language to do 
the repetition, substituting a variable which increases in 
value each time it repeats. In Python it looks like this:

>>>for i in range(1,13):
...    print "%d x 12 = %d" % (i, i*12)

Note 1: we need the range(1,13) to specify 13 because range() 
generates from the first number up to, but not including, 
the second number. This may seem somewhat bizarre at first 
but there are reasons and you get used to it.

Note 2: The for operator in Python is actually a foreach operator 
in that it applies the subsequent code sequence to each member 
of a collection. In this case the collection is the list of 
numbers generated by range(). You can check that by typing:

>>> print range(1,13)

you will see that you get a Python list of numbers back.

Here's the same loop in BASIC:

FOR I = 1 to 12
    PRINT I, " x 12 = ", I*12

This is much more explicit and easier to see what is happening. 
However the Python version is more flexible in that we can loop 
over a set of numbers, the items in a list or any other 
collection (e.g. a string). 

Find it at:


Alan G.