Rocket has to run a systems check on all twelve stations in Mission Control. His program has twelve print lines, almost exactly the same, one after another.
"It works," he says, scrolling down. "But if we add a thirteenth station, I have to copy another line. And another for the next one."
Raven counts the lines with her pencil. "What do you notice?" she asks. "Only the station number changes. Everything else is the same each time."
Nova spins in a slow circle. "I found a pattern," she says. "When a line repeats with one small change, a loop can do the repeating for you."
Rocket deletes eleven lines and keeps just one.
A for loop runs its indented block once for each value. The line ends with a colon, and the block is indented, just like if.
range(3) gives the numbers 0, 1 and 2. It starts at 0 and stops just before 3, so the loop runs three times.
# check_loop.py
for station in range(3):
print("Checking station", station)
print("All checks done") Checking station 0 Checking station 1 Checking station 2 All checks done
| You write | Numbers you get | Why |
|---|---|---|
| range(5) | 0, 1, 2, 3, 4 | Starts at 0, stops before 5 |
| range(1, 6) | 1, 2, 3, 4, 5 | Starts at 1, stops before 6 |
| range(10, 0, -2) | 10, 8, 6, 4, 2 | Steps down by 2, stops before 0 |
The stop number is never included. To count from 1 to 12, write range(1, 13).
The loop variable takes each value from the range in turn. You can use it inside the block for math, not just for printing.
A step of 5 makes range jump by fives. This is handy for checkpoints, timers and tables.
# checkpoints.py
for km in range(0, 21, 5):
print("Checkpoint at", km, "km")
for n in range(1, 5):
print(n, "squared is", n * n) Checkpoint at 0 km Checkpoint at 5 km Checkpoint at 10 km Checkpoint at 15 km Checkpoint at 20 km 1 squared is 1 2 squared is 4 3 squared is 9 4 squared is 16
| Statement | True or false? |
|---|---|
| range(4) gives 1, 2, 3, 4. | ? |
| range(1, 4) gives 1, 2, 3. | ? |
| The loop variable can be used in math inside the block. | ? |
| range(10, 0, -5) gives 10 and 5. | ? |
One loop line replaced many copied lines. Tomorrow you will use loops to add things up.