In this topic students learn to repeat lines of code a set number of times,
using for loops and range.
Be able to read, comprehend, trace, adapt and create Python code that:
for loopsrange with a start, a stop and a stepThis chapter has no slide deck. It was written for Dodona from new material by the course author, after the rest of the course had been converted.
This chapter is the second half of iteration. The previous chapter covers
while loops, where the program repeats until something changes; this one
covers for loops, where the number of repetitions is known before the loop
starts.
The exam specification calls these count controlled and condition
controlled iteration, and both activities and exercises use those terms
alongside for and while. It is worth being explicit with students that this
is one idea with two shapes, and that the question to ask of any repeated task
is “do I know how many times?”.
The pedagogical argument for teaching while first, as this course does, is
that a while loop makes every part of the mechanism visible: the counter is
created, compared and changed in three separate places, and forgetting the third
gives an infinite loop. A for loop does all three at once. Students who have
seen the long form first tend to read for counter in range(10): as the short
form of something they already understand, rather than as new magic.
range(10) counts from 0 and stops before 10, so it produces ten values.
The count is the number in the brackets, which is usually what students want.range(start, stop) counts from the first number and stops before the second.
This is where almost every mistake in this chapter comes from.range(start, stop, step) changes the size of the step. Leaving the step out
means a step of 1.range(0) runs the body zero times, which matters as
soon as the user decides how many repetitions there are.range(1, 20) repeats 19 times, not 20. Students who count
the numbers rather than reading the range get this right; students who read
“1 to 20” do not. The Modify task exists mainly to make this mistake visible.range(start, end + 1). The Investigate task asks students to
explain the + 1 in their own words, which is a better check of understanding
than asking them to write it.total = 0 has to
be before the loop. Inside it, the total is reset on every repetition and the
program prints only the last number. This is worth tracing on the board.int(), three answers of 7, 13 and 128
produce Total is 713128 rather than Total is 148. The test suite includes
exactly that case, so students see the difference rather than being told.