Programming repeating algorithms: the for statement
When the same job must be done many times, repetition (a loop) is used; if the number of repetitions is known beforehand, for is handy. It is written for i in range(start, stop, step): and the loop body follows on the next line indented by 4 spaces. i is the loop variable and takes the next value in every iteration; start is the starting value (0 if not given), step is the step (1 if not given), and stop is not included in the loop: range(1, 6) gives the numbers 1, 2, 3, 4, 5. For decreasing order the step is negative: range(5, 0, -1) goes from 5 to 1. A loop can be written inside a loop; when the outer loop turns once the inner loop turns completely, so a 3 × 3 loop is run 9 times. To find a sum, s = 0 is written before the loop and s += i is done in the loop.
i = 0, 3, 6, 9, 12
Repetitions: 5 · sum = 30
the stop value itself is not included
A sports teacher put a marker every 5 metres along a 50-metre line, so the markers stood at 0, 5, 10 and so on up to 50. The pattern “start, stop, step” described the line exactly.
Gardeners, builders and programmers repeat the same step many times to make tables or rows.
On paper write the numbers from 3 to 30 in steps of 3 and count them. Show the rule “previous + 3” for each step.
1s = 0 2for i in range(1, 11): 3 s += i 4print(s) 5 6for i in range(1, 4): 7 for j in range(1, 4): 8 print(i * j, end=" ") 9 print()
55 1 2 3 2 4 6 3 6 9
1for i in range(1, 16, 3): 2 print(i, end=" ") 3 4for i in range(9, 0, -2): 5 print(i, end=" ")
1 4 7 10 13 9 7 5 3 1
“Loop counter”: the group takes 6 range() lines (range(5), range(2, 9), range(1, 20, 5), range(8, 0, -2) ...), first finds the number of iterations and the numbers in the notebook, and then checks them in IDLE with list(range(...)) or a loop.