[Tutor] FOR loops

Corran Webster cwebster@nevada.edu
Sat, 2 Oct 1999 09:12:40 -0700 (PDT)

> Hello, I am a beginner at python and have been learning it from the
> O'reilly book 'Learning Python'
> it has been pretty easy to understand for someone who has never
> programmed before, but it stumps me sometimes.......

I think it is fair to say that "Learning Python" is aimed more at people
who already know some programming but don't know any python than at
absolute beginners.  Which doesn't mean that you won't learn a great deal
from it, but be prepared for other stumbling blocks along the way.

It would be very nice to have a "Learning Programming with Python" type of
book given that python is a very good language for beginners.

> Thats where this
> 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.

The one-line summary: a for loop takes the elements of a list, one at a
time, and does something with them.  For example:

mylist = ["Bruce", "Sheila", "Kevin"]

for person in mylist:
    print person

will go through the list of names, and print each out.  It will produce
the output


The variable "person" first takes the value "Bruce" and prints it out; 
then the loop goes back and gives it the value "Sheila" and prints it out;
and finally it gives it the value "Kevin" and prints it out.

It is very common in practise to have a list which you want to do
something to each element - for example, doing something with each line in
a file you have read; or doing something to each item in some list of

Another common use of the for loop is to do something with a range of
numbers using the range function:

for i in range(10):
  print i, i*i

This will print a list of numbers and their squares from 0 through to 9,
inclusive.  If you want from 1 to 10, you would need to use range(1,11)

Here the range(10) function returns the list [0,1,2,3,4,5,6,7,8,9]; the
the for loop goes through and assigns each element of the list to i
sequentially - first 0, than 1, then 2, and so on up to 9.  For each value
of i, the print statement prints out i and it's square (i*i).

Also sometimes you just want to do something repeatedly.  In this case you
can use a range, but ignore the variable - for example:

times = 10

for i in range(times):
    print "This will print", times, "times"

Notice that i is not referred to inside the for loop; this will simply
print out the same thing over and over a grand total of 10 times.

Some more examples for you to think about:

age = {'Bruce": 43, "Sheila": 32, "Kevin": 8}

for person in age.keys():
    print person, "is", age[person], "years old"

names = {"Bruce", "Sheila", "Kevin"]

for name in names:
    if name == "Bruce":
        print "Bruce is in the list!"

Hope this sheds some light.