☰ Contents · Computing

Logical expression practice and the if…else operator

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

Programming branching algorithms: the if…else statement

Textbook: pp. 76–78
GoalKnows branching algorithms and the structure of the if and if…else operators, and writes, following the indentation rule, a program that chooses one of two paths by one condition.
New words
branching algorithm: the choice of which commands to carry out depends on a condition · tarmoqlanuvchi algoritmif: runs its block only if the condition is True · ifelse: the block run when the if condition is False · elseblock: the lines under if or else, indented by four spaces · blok
Explanation

In a branching algorithm a condition is checked and, depending on the result, one or another group of commands is carried out. In Python this is written as if condition: with a colon after the condition, and the lines to be carried out go on the next line indented by 4 spaces – this is called the if block. If the condition is True the block is run; otherwise it is skipped. An extra block is given with else:, which is run when the condition is False; else has no condition of its own and stands level with if, that is with the same indent. Indentation here is a rule of the language: if you forget it, an IndentationError appears. In a flowchart the condition is a rhombus with two arrows marked “yes” and “no”. After the two paths they join again and the program continues from the common part.

Worked examples
Positive or not: n = int(input()) ⏎ if n > 0: ⏎     print("musbat") ⏎ else: ⏎     print("musbat emas") If -3 is typed the condition is false, so the else block works and musbat emas is printed.
Even or odd: n = int(input()) ⏎ if n % 2 == 0: ⏎     print("juft") ⏎ else: ⏎     print("toq") 7 % 2 = 1, the condition is false, so toq is printed. With a discount: s = int(input()) ⏎ if s >= 100000: ⏎     s = s - s // 10 ⏎ print(s) if the sum is 100000 or more, a tenth is subtracted; for 150000 the result is 135000.
Class activity

“Human program”: the class is split in two halves; one half holds “condition” cards (age >= 14, number even), the other walks the “yes” or “no” paths and acts out a flowchart live.

Practice
1
Which error appears if print(x) is written without an indent after if x > 3:?
2
A bill sum s is typed. If s reaches 100000, a 10% discount is given. Write the program (135000 for 150000).
3
What is y equal to after this program runs? x = 4 ⏎ if x % 2 == 0: ⏎     y = x // 2 ⏎ else: ⏎     y = 3 * x + 1
4
Why is no condition written after else?