☰ 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
40

Practical lesson: the elif statement

Textbook: p. 81
GoalIn the practical lesson, uses a counter variable in branching programs, orders two numbers and chooses a name by a number with an elif chain.
New words
counter: a variable that starts at 0 and grows by 1 each time something is found · hisoblagichk += 1: the short form of increasing the counter by one · k += 1ordering: printing two numbers from the larger to the smaller (or the reverse) · tartiblashelif chain: a ladder of conditions where only the first true block is run · elif zanjiri
Explanation

A counter is a variable used to count how many elements have a given property. Its starting value is set to 0, k += 1 is done every time the condition holds, and k is printed at the end. With three numbers a separate if is written for each, because each number must be checked independently; elif would be wrong here. To order two numbers so that the larger is printed first, if…else is enough: if a >= b then print(a, b), otherwise print(b, a). Choosing a name by a number is a usual elif-chain task: for example, for a traffic light 1 – red, 2 – yellow, 3 – green, and for any other number an error message is printed in else. Also test the program with border values (1, 3, 0, 4).

Worked examples
Counting even numbers: a = input().split() ⏎ k = 0 ⏎ if int(a[0]) % 2 == 0: ⏎     k += 1 ⏎ if int(a[1]) % 2 == 0: ⏎     k += 1 ⏎ if int(a[2]) % 2 == 0: ⏎     k += 1 ⏎ print(k) If 4 7 10 is typed, there are two even numbers, so 2 is printed.
Ordering: a = int(input()) ⏎ b = int(input()) ⏎ if a >= b: ⏎     print(a, b) ⏎ else: ⏎     print(b, a) For 3 and 8 the larger comes first: 8 3.
Class activity

“Counting contest”: teams write a “how many are greater than 5” program for three numbers; the team that first writes a program that works and is correct for all border values wins.

Practice
1
How many of the numbers -3, 5 and 0 are positive?
2
The number of a traffic light is typed: 1 – “qizil: to‘xtang” (red: stop), 2 – “sariq: tayyorlaning” (yellow: get ready), 3 – “yashil: yuring” (green: go), any other number – “xato” (error). Write the program.
3
What does a program that prints two numbers as “larger first, then smaller” print for 5 and 5?
4
Why must the starting value of a counter be 0?