Lessons 42–43 · 2 lessons · M. R. Fayziyeva, D. M. Sayfurov, N. S. Xaytullayeva. Informatics and Information Technologies, Grade 9. “Nashriyot uyi Tasvir”, Tashkent, 2020
42
Practical lesson: the for statement
Textbook: p. 85
GoalIn the practical lesson, prints multiples with a for loop, finds sums and products, and counts the numbers with a required property among those given.
New words
sum accumulator: a variable that starts at 0 and has the values added to it in the loop · yig‘indi hisoblagichiproduct accumulator: starts at 1 and is multiplied in the loop · ko‘paytma hisoblagichifactorial n!: the product 1 · 2 · … · n · faktorialmultiple: the numbers x, 2x, 3x, … · karrali son
Explanation
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.
Worked examples
Multiples: x = int(input()) ⏎ n = int(input()) ⏎ for i in range(1, n + 1): ⏎ print(x * i, end=" ") For x = 8, n = 6, 8 16 24 32 40 48 is printed.
Factorial: n = int(input()) ⏎ p = 1 ⏎ for i in range(1, n + 1): ⏎ p *= i ⏎ print(p) For n = 5, p becomes 1, 2, 6, 24, 120 in turn and 120 is printed.
Class activity
“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.
Practice
1
How many values does range(-10, 10, 3) give?
7
2
What is the result of a loop that finds the sum 12 + 15 + 18 + … + 60?
612
3
n is typed, then n numbers are typed. Write a program that prints how many of them are positive.
n = int(input()) ⏎ k = 0 ⏎ for i in range(n): ⏎ x = int(input()) ⏎ if x > 0: ⏎ k += 1 ⏎ print(k)
4
Why is the starting value of a product accumulator 1 and that of a sum accumulator 0?
1 does not affect multiplication and 0 does not affect addition; any other value changes the result.