CODING
ADVENTURE
0 / 12 completed

FIELD NOTE 06 / BEGINNER PYTHON

Python for and while loops: repeat with a reason

A loop repeats a block of instructions. A for loop visits a sequence; a while loop repeats while a condition is true.

The idea

If you have three clues, you could write three almost-identical print lines. A loop separates the collection from the instruction to perform on each item. That makes the idea easier to extend: a fourth clue does not require a fourth copy of the instruction. Follow the loop one pass at a time, writing down which value the loop variable currently holds.

A tiny experiment

PYTHON 3PREDICT BEFORE YOU RUN
clues = ["key", "receipt", "map"]
for clue in clues:
    print("Inspect: " + clue)
print("All checked.")
Run and change this example ↗
Reveal the expected output
Inspect: key
Inspect: receipt
Inspect: map
All checked.

Read it one step at a time

  1. Square brackets create a list. Here the entries are strings.
  2. for gives clue each list item in turn. The indented instruction runs once for each item.
  3. The final print is outside the loop, so it runs once after all three passes. range(3) can instead supply 0, 1 and 2.

Make one change

Move the last print inside the loop by adding four spaces. How many times will it appear?

Check your thinking

All checked. appears three times, once after each clue.

Keep following the trail

Sources & further reading

Companion notes for Coding Adventure by James Colby. Historical claims link to their sources; the examples are written for this learning trail.