Skip to main content

9.2) Repeating Actions, The For Loop


If you want to repeat a task several times in a program, you can do this with loops. In Part 1, we learned how to use a while loop. The for loop is another type of loop which allows you to repeat an action a fixed number of times. It can go through the items of a sequence, like a string or list, repeating the task for each item. A simple for loop is written like this:

for <target> in <sequence>:
    <statement>

Notice the colon (:) and the indentation. When this loop is executed, the target is assigned the elements of the sequence one by one and the statement is executed. The statement usually makes use of the target. The sequence can be a string, list or tuple. For example:

for character in 'abc':
   print character

prints the following:

a
b
c

and,

for a in [1,2,3]:
   print a**2

prints the following:

1
4
9

Type out these loops in a program and run it in IDLE. Then type the loop interactively in IDLE.