Repeat with for and range
Visit every reading with a for loop, then use range() when the program needs a known number of repetitions. Trace zero, one, and several iterations around the excluded stop value.
The readings now form one ordered sequence:
readings = [18, 21, 20, 23]
A for loop can run the same block once for each value in that list.
Visit Each Reading
The name reading is the loop variable. On each iteration, it refers to
the next value from readings. The indented line is the loop body.
| Iteration | Current reading | New output |
|---|---|---|
| 1 | 18 | reading: 18 |
| 2 | 21 | reading: 21 |
| 3 | 20 | reading: 20 |
| 4 | 23 | reading: 23 |
The list order determines the visit order. The loop body runs four times because the list contains four values.
Q1. Trace direct iteration
What does this program display?
Select one choice, then check.
HintWrite one row per value
Evaluate reading - 20 for 18, then 20, then 23.
SolutionThe three differences appear in order
The differences are -2, 0, and 3, and each iteration prints one of them.
Repeat a Known Number of Times
Sometimes the values themselves do not matter; only the number of repetitions
does. range(stop) produces integers beginning at 0 and ending just before
stop:
0
1
2
3
The stopping value 4 is excluded. This boundary makes three small cases useful:
| Source | Produced values | Iterations |
|---|---|---|
range(0) | none | 0 |
range(1) | 0 | 1 |
range(4) | 0, 1, 2, 3 | 4 |
Use direct iteration when the program needs each reading. Use range() when
the program needs a known number of repetitions or the generated integers.
Q2. Check the excluded stop
How many times does the loop body run?
Compute it first, then check your number.
HintExpand the range
Write the values produced by range(3) before counting them.
SolutionThe body runs three times
The loop variable receives 0, 1, and 2. The excluded stop value 3 is never visited.
Q3. Choose the clearer loop
You need to classify every value in readings. Which loop header states that
job most directly?
Select one choice, then check.
HintName the needed value
The body needs a reading, not merely a repetition number.
SolutionIterate over readings
for reading in readings: visits each value and makes the loop's purpose
visible without introducing an unnecessary position.
A for loop repeats once per value in a sequence; range() supplies a known
count of integers with an excluded stop. Repeated output is useful, but the
report also needs a total and count that survive from one iteration to the
next.