Practical lesson: the for statement
Most loop tasks fit one of three patterns. The first is printing: to print n multiples of x we run the loop variable i from 1 to n and print x * i. The second is accumulating a sum: s = 0 before the loop, and s += i or s += i * i in the loop. The third is multiplying: here the starting value is 1, otherwise the product would always stay zero; this is how n! is found, for example 5! = 120. In counting tasks where the numbers are typed one by one, n is read first and then input() is called n times with for, and in each pass a counter is increased depending on a condition. Work out beforehand how many times the loop runs: (stop – start) divided by step, rounded up.
After each round of a class quiz, a pupil added that round’s score to a running total on the board. Because every round was added in the same way, the final total was easy to check.
Stock-checkers, librarians and programmers repeat one operation in order to find a total or a count.
On paper find the sum of the even numbers from 1 to 12 and write the order of adding. Check the total yourself.
1x = int(input()) 2n = int(input()) 3for i in range(1, n + 1): 4 print(x * i, end=" ")
8 16 24 32 40 48
1n = int(input()) 2p = 1 3for i in range(1, n + 1): 4 p *= i 5print(p)
120
“Loop workshop”: each group chooses one pattern (printing, summing, multiplying, counting), invents its own task and shows the solution to another group, which tests it with 2 different values.