Specialty Digest

Global English editionLearners’ Study Dashboard — in development
The Knowledge Library for All

Flashcards: open the module flashcards (end-of-module review with workplace questions).

Online Courses / University Track / Python from Zero

Module 3 · Lesson 4 · Core

Choosing a loop and tracing it by hand

Choose between for and while, trace a loop with a table and avoid the off-by-one error.

  • 50 minutes
  • Serves O3
  • Assumes M3.L3

Phase 1: Prepare

Step 1 Warm-up recall

From M3.L3: where should a running total start?

Private: nothing you type here is sent or stored.

Step 2 Learning goal

By the end of this lesson you can:

  • choose for or while for a task (Foundation);
  • trace a loop with a table (Core);
  • spot an off-by-one error (Core).

Phase 2: Teach

Step 3 A familiar example

A schedule with a fixed number of days uses for. A job that repeats until a stock level runs out uses while. The first knows how many in advance; the second does not.

Step 4 Clear explanation

Use a for loop when you know how many times to repeat, or you have a sequence to walk through. Use a while loop when you repeat until something changes and you do not know how many passes it takes.

To check any loop, trace it by hand with a table, one row per pass:

x = 10
while x > 0:
    x = x - 4
    print(x)
Passx at startx after x = x - 4Printedx > 0 ?
11066True
2622True
32-2-2False, loop ends
6
2
-2

Note that -2 is printed, because the check happens before the pass, not after the update. The most common loop bug is the off-by-one error: a loop that runs one time too many or too few.

range(5): 0 to 40range(1, 5): 1 to 41range(1, 6): 1 to 52The stop value is never reached
Count the values: range(1, 5) gives four values, 1 to 4, because the stop value is never reached.

A loop can sit inside another. For each pass of the outer loop, the inner loop runs completely:

for i in range(1, 3):
    for j in range(1, 4):
        print(i * j)
1
2
3
2
4
6

Here the outer loop runs 2 times and the inner 3 times each, so the print line runs 2 × 3 = 6 times.

Step 5 Worked example (4 marks)

How many lines does for a in range(3): for b in range(4): print(a, b) print?

  1. The outer loop runs 3 times. (1 mark)
  2. The inner loop runs 4 times for each of them. (1 mark)
  3. 3 × 4 = 12. (1 mark)
  4. Answer: 12 lines. (1 mark)

Go deeper: the professor's notes

Trace with a table. Check the first pass and the last pass.
First

Is it right?

Last

Is it right?

Growth

Does error grow?

Rowper passUpdatevariablesCheckfirst and lastCompareexpected
Trace

Error

HoursError (s)
80.0275
1000.3433

At work: A long-running process

It runs for days without a restart.

  1. Trace the first hour.
  2. Trace the last hour.

What a careful practitioner decides. Test long runs, not only short ones.

Phase 3: Practise

Step 6 Learner practice (instant-marked)

1. You know the number of passes in advance. Use:

2. You repeat until the user enters a valid value. Use:

3. An off-by-one error is a loop that runs:

4. An outer loop of 2 and an inner loop of 5 run the inner body:

Phase 4: Close

Step 7 Recap

  • for for a known count; while for an unknown count.
  • Trace with a table, one row per pass.
  • Check the first and last pass for off-by-one errors.

Step 8 Exit ticket (ungraded)

Trace x = 7, while x > 0: x = x - 3, print(x). List the printed values.

Private: nothing you type here is sent or stored.

Step 9 Go further (Extension)

Trace the nested loop with range(1, 4) outside and range(1, 3) inside.

In industry: Patriot: the error grows with the count

The Patriot clock error was about 0.0275 seconds after 8 hours and about 0.3433 seconds after 100 hours. The same tiny rounding was repeated at every tick.

Link to this lesson. Trace a loop for the first pass and for the last pass. The two can look very different.

Source: Skeel, Roundoff Error and the Patriot Missile; GAO/IMTEC-92-26

Common mistakes

MistakeWhy it fails
Skipping the traceRun it by hand before running it on the machine.
Counting values as stop minus onerange(1, 5) has 4 values, not 5.
Mixing up inner and outerThe inner loop finishes first on every outer pass.

Limits. Tracing shows what a program does for one input; use several inputs.

Flashcards for this lesson (3)

Tap a card to reveal the answer. Read the question, answer it aloud or in writing first, then check yourself against the explanation.

Card 1 of 3 · How do you find an average with a loop?
TotalsumCountitemsDivideafter
Average

Total the values and count the items in the loop, then divide after the loop: average = total / count. Divide by the number of items, not the last value.

Card 2 of 3 · What is an off-by-one error?
range(1, 5)4 valuesCheckfirst and lastFixadjust stop
Off by one

A loop that runs one time too many or too few, often from misreading range. range(1, 5) has 4 values, not 5. Check the first and the last pass.

Card 3 of 3 · How do you trace a loop by hand?
Roweach passColumnsvariablesCompareexpected
Trace table

Draw a table with one row per pass and a column for each changing variable. Write the expected output first, then run the code. It is how you find a loop bug before it reaches users.

Review with flashcards

Test yourself on this module with workplace flashcards and detailed answers.

Open the module flashcards