☰ Contents · Computing

If…else practice and the elif operator

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

Practical lesson: the if…else statement

Textbook: p. 78
GoalIn the practical lesson, programs tasks on divisibility, finding the larger number and changing a value by a condition with the if…else operator.
New words
divisibility condition: a % b == 0 means a is divisible by b with no remainder · bo‘linish shartimaximum: the larger of two or more numbers · maksimumabsolute value (modulus): the number without its sign · modulconditional assignment: a variable receives a value depending on a condition · shartli o‘zlashtirish
Explanation

This lesson solves three typical tasks. The first is divisibility: if a is divisible by b with no remainder then a % b == 0, otherwise the remainder is not zero. The second is finding the larger of two numbers: if a > b then m = a, otherwise m = b – on both paths m receives a value, so print(m) always works. The third is finding the absolute value of a number: we change the sign only if x is negative, so else is not needed. Before working on a task draw the flowchart: each condition is one rhombus and each path is one block. Test the program with at least two different values: once with the condition true and once with it false. This two-sided test is the main check of branching programs.

Worked examples
Checking divisibility: a = int(input()) ⏎ b = int(input()) ⏎ if a % b == 0: ⏎     print("ha") ⏎ else: ⏎     print("yo‘q", a % b) For 17 and 5 the remainder is 2, so yo‘q 2 is printed. Finding the larger: a = int(input()) ⏎ b = int(input()) ⏎ if a > b: ⏎     m = a ⏎ else: ⏎     m = b ⏎ print(m) For 8 and 15, 15 is printed.
Temperature: t = int(input()) ⏎ if t >= 25: ⏎     print("issiq") ⏎ else: ⏎     print("salqin") For 30 degrees issiq is printed. Absolute value: x = int(input()) ⏎ if x < 0: ⏎     x = -x ⏎ print(x) If -9 is typed, 9 is printed; a positive number stays unchanged.
Class activity

“Two-sided test”: each group chooses two test values for its program (one making the condition true and one false), predicts the result in advance and then checks in IDLE.

Practice
1
What does this program print? a = 12 ⏎ b = 5 ⏎ if a % b == 0: ⏎     print(a // b) ⏎ else: ⏎     print(a % b)
2
Write a program that reads a temperature and prints “issiq” if it is 25 or higher and “salqin” otherwise.
3
Write a program that finds the absolute value of a number (9 for -9, 4 for 4).
4
Why is else not needed in the absolute value task?