0%

Chapter 7

Repeating Work with Loops

Repeat Without Copying

At the end of the last chapter you printed your organizer with four lines that were almost identical:

print(f"1. {items[0]}")
print(f"2. {items[1]}")
print(f"3. {items[2]}")
print(f"4. {items[3]}")

That worked, and writing it out was deliberate. It also has a problem you can already see. The program can only print four items. Add a fifth and it stays invisible until you write another print line. Remove one and the program stops with an .

The number of items belongs to the data. Right now it is frozen into the code.

The shape of repeated work

Look at the four lines again and notice what actually changes between them. The word print does not change. The does not change. Only two things move: the number, and the inside the brackets.

Whenever you find yourself writing nearly the same line several times, Python has a better tool. It is called a , and it lets you write the repeated work once.

A first for loop

Here is the same idea as a loop:

Try it

Four lines of output, from two lines of code.

Read the first line out loud as an English sentence: “for each item in items.” That is close to what Python does. It takes the , hands you the first , runs the indented block, then hands you the next value, and continues until the list is finished.

The parts of the line

for item in items:
PartWhat it is
forThe keyword that starts the loop
itemThe loop , a name you choose
inThe keyword that separates the name from the collection
itemsThe list Python will walk through
:The colon that ends the line, as in an statement

Everything indented under that line is the loop body. Python runs the whole body once per value.

The indentation rule is the one you already learned with if. Indented lines belong to the loop. Lines back at the left margin run after the loop has finished:

Try it

Done appears once, at the end. It is not indented, so it is not part of the repeated work.

You choose the loop variable name

item and color are not special words. They are ordinary variable names, and Python assigns each value to that name in turn. Choose a name that describes one member of the collection:

Try it

A plural name for the list and a singular name for the loop variable reads well and helps you keep the two apart.

The loop does not care how many

This is the part that fixes the organizer problem. The same two lines work for three values or thirty:

Try it

Nothing in the loop mentions a count. Add or remove items from the list and the loop simply follows.

If the list is empty, there are no values to visit, so the body runs zero times. Lines after the loop still run. Try replacing tasks with [] in the example above.

How many times does the indented line run?

sizes = [8, 12, 16, 20]
for size in sizes:
    print(size)

Which line or lines belong to the loop body?

animals = ["otter", "heron"]
for animal in animals:
    print(animal)
    print("Seen")
print("Walk finished")

What you gained

The loop is short, but the change in what your programs can do is large. Until now, a program did a fixed amount of work that you typed out by hand. From here, one small block of code can handle a collection of any size.

In the next lesson you will write loops yourself and watch the loop variable change value on every pass.

Task

Run each example and try changing a before you continue. Before moving on, make sure you can explain:

  • which parts of the four organizer print lines were actually repeated;

  • what the holds during each pass through the body;

  • how Python decides which lines are inside the loop and which come after it;

  • why adding an item to the list does not require changing the loop.