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.

IterationCurrent readingNew output
118reading: 18
221reading: 21
320reading: 20
423reading: 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?

Choose one

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.

Not attempted
Review

Not marked done.

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:

SourceProduced valuesIterations
range(0)none0
range(1)01
range(4)0, 1, 2, 34

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.

Not attempted
Review

Not marked done.

Q3. Choose the clearer loop

You need to classify every value in readings. Which loop header states that job most directly?

Choose one

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.

Not attempted
Review

Not marked done.

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.

Pause and reflect

In your own words, note what you understood, what remains unclear, or what you want to revisit. The note stays with this lesson.

0 of 3 exercises marked done

Review

Not marked done.