☰ Contents · Computing

Branching practice and the for loop

Lessons 40–41 · 2 lessons · M. R. Fayziyeva, D. M. Sayfurov, N. S. Xaytullayeva. Informatics and Information Technologies, Grade 9. “Nashriyot uyi Tasvir”, Tashkent, 2020
41

Programming repeating algorithms: the for statement

Textbook: pp. 82–84
GoalKnows the structure of the for loop and range(start, stop, step), counts the repetitions, writes a loop that finds a sum, and explains how nested loops work.
New words
for loop: a counted loop used when the number of repetitions is known beforehand · for siklirange(): produces the numbers for a loop; the stop value is not included · range()iteration: one pass through the loop body · iteratsiyanested loop: a loop inside the body of another loop · ichma-ich sikl
Explanation

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.

Worked examples
Sum: s = 0 ⏎ for i in range(1, 11): ⏎     s += i ⏎ print(s) The sum of the numbers from 1 to 10 is 55. A table: for i in range(1, 4): ⏎     for j in range(1, 4): ⏎         print(i * j, end=" ") ⏎     print() The result is 3 rows: 1 2 3, 2 4 6, 3 6 9.
Step: for i in range(1, 16, 3): ⏎     print(i, end=" ") 1 4 7 10 13 is printed (16 is not included). Decreasing: for i in range(9, 0, -2): ⏎     print(i, end=" ") 9 7 5 3 1 is printed (0 is not included).
Class activity

“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.

Practice
1
How many values does range(3, 20, 4) give?
2
Write a loop that prints the even numbers from 2 to 20 on one line.
3
Find the sum of the squares of the numbers from 1 to 5.
4
Why is the number 6 not in range(1, 6)?