Easier to read with cream paper, a tint, more contrast or larger text? Choose your colours and text, once, for every page.

Free lesson

For and while loops in Python

After this lesson: I can repeat work with for and while loops.

55 min lesson4 commandsEveryday Linux commands lab: the thirty commands engineers type from memory

Doing the same job a hundred times

A loop repeats a block of code, so a Python program can do one job many times without you writing it out again. It is how a program adds up a column of prices, checks every line of a log or counts the days to a deadline.

Typing print a hundred times would be silly. A loop does it in two lines.

By the end of this lesson

Note

I can repeat work with for and while loops.

Key words

WordWhat it meansExample
Loopcode that repeats
Iterationone pass through a loop
Rangea run of whole numbers made by range()range(1, 6)
Accumulatora variable that builds up a total as a loop runstotal
Infinite loopa loop that never ends
Breaka command that leaves a loop early

The cells students fill in are left blank in this preview.

A for loop repeats once for each value

A for loop takes a run of values and repeats its indented lines once for each. The name after for holds the current value.

range makes the run of whole numbers. range(5) gives 0 to 4. range(1, 6) gives 1 to 5, because it stops before the second number.

Worked example: what range gives

You writeYou getNumber of passes
range(5)0, 1, 2, 3, 45
range(1, 6)1, 2, 3, 4, 55
range(2, 10, 2)2, 4, 6, 84
range(10, 0, -3)10, 7, 4, 14

The cells students fill in are left blank in this preview.

Print three numbers

Command
python3 -c "for n in range(3): print(n)"

Shown here, not run. Create a free account to press Run and type it into your own lab’s terminal.

Five rounds

Code: python
for n in range(1, 6):
    print("Round", n)
# Change 6 to 9 and run again.

A common mistake

Warning

Many people think range(1, 5) includes 5. It stops before 5, so it gives 1, 2, 3 and 4. To count up to 5, write range(1, 6). The end number is never part of the run.

An accumulator builds up a total

To add up many values, make a variable before the loop and start it at 0. Inside the loop, add each value to it. This variable is an accumulator.

After the loop it holds the whole total. The trace table shows each pass.

Worked example: adding 1 to 4

Passntotal after the pass
Before the loopnone0
111
223
336
4410

The cells students fill in are left blank in this preview.

Watch the total grow

Code: python
total = 0
for n in range(1, 5):
    total = total + n
    print("n is", n, "and total is", total)
print("Final total:", total)

Save a loop program as a file

Command
printf 'total = 0\nfor n in range(1, 5):\n    total = total + n\nprint(total)\n' > total.py

Shown here, not run. Create a free account to press Run and type it into your own lab’s terminal.

Run the file

Command
python3 total.py

Shown here, not run. Create a free account to press Run and type it into your own lab’s terminal.

A while loop repeats on a condition

A while loop does not need a run of values. It tests a condition before every pass, and it repeats while the condition is True.

Something inside the loop must change the answer, or it never stops. A loop that never ends is an infinite loop. In a terminal, press Ctrl and C together to stop one.

Saving until the balance is enough

Code: python
balance = 100
months = 0
while balance < 150:
    balance = balance + 20
    months = months + 1
print(months, "months to reach", balance)
# Change 150 to 200 and run again.

break leaves a loop early

Sometimes you can stop as soon as you find what you want. The command break leaves the loop at once, and the program carries on after it.

The next program searches for the first number whose square is over 50.

Stop at the first square over 50

Code: python
for n in range(1, 100):
    if n * n > 50:
        print("First square over 50 is", n * n)
        break

A nested loop runs inside another loop

A loop can sit inside another loop. The inner loop runs all its passes for each pass of the outer one.

With 2 passes outside and 3 inside, the inner lines run 2 times 3, which is 6 times.

Six lines from two loops

Code: python
for row in range(1, 3):
    for col in range(1, 4):
        print(row, "x", col, "=", row * col)
# The inner loop runs fully for each pass of the outer one.

A small table from one line

Command
python3 -c "for a in range(1, 4): print(a, a * 2, a * 3)"

Shown here, not run. Create a free account to press Run and type it into your own lab’s terminal.

Going further

Change total.py so that it adds the even numbers from 2 to 20. You can do it with a third number in range, or with an if inside the loop.

Write down the answer you expect first. A trace table for the first three passes is enough to check it.

About this lab and its source: Everyday Linux commands lab: the thirty commands engineers type from memory

Teaching a class? Set this module for your students with a teacher guide, marked assignments and a lab for every student.