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
39
Programming branching algorithms: the elif statement
Textbook: pp. 79–80
GoalChecks several conditions in turn with the elif operator, knows the structure and indentation of a nested if, and writes programs with a choice of many paths.
New words
elif: “else if”, the next condition that is checked only if the earlier ones were False · elifmulti-way choice: a chain of if, elif and else where exactly one block is run · ko‘p yo‘lli tanlovnested if: an if placed inside the block of another if, with one more indent · ichma-ich iforder of conditions: the first True one is chosen, so the order matters · shartlar tartibi
Explanation
When one of many cases must be chosen, a chain of if, elif and else is used: Python checks the conditions from top to bottom, runs the first block that turns out True and skips the rest; if none is True, else works. So the order of the conditions matters: once the winter months have been separated, the condition m <= 5 matches only the spring months. The number of elif parts is not limited, and else is optional. A choice operator like CASE in other languages is replaced in Python by this method. An if may contain another if: the inner if is written with 4 more spaces of indent than the outer one, otherwise it becomes a separate condition. The inner condition is checked only when the outer one is True.
Worked examples
Name of the season: m = int(input()) ⏎ if m == 12 or m == 1 or m == 2: ⏎ print("qish") ⏎ elif m <= 5: ⏎ print("bahor") ⏎ elif m <= 8: ⏎ print("yoz") ⏎ else: ⏎ print("kuz") For month 7 the winter condition is false, m <= 5 is false, m <= 8 is true – yoz is printed.
Nested if: n = int(input()) ⏎ if n > 0: ⏎ if n % 2 == 0: ⏎ print("musbat juft") ⏎ else: ⏎ print("musbat toq") ⏎ else: ⏎ print("musbat emas") 9 is positive, so the inner condition is checked; 9 % 2 = 1, so musbat toq is printed. If a negative number is typed, the inner if is not checked and musbat emas is printed.
Class activity
“Mark translator”: the group writes a program that reads a mark from 1 to 5; with an elif chain it prints 5 – “a’lo” (excellent), 4 – “yaxshi” (good), 3 – “qoniqarli” (satisfactory), 2 – “qoniqarsiz” (unsatisfactory), and for any other number else prints “no such mark”.
Practice
1
What does the season program print for month 4?
bahor (spring)
2
Write a program with elif that finds the sign of a number (“musbat”, “manfiy”, “nol”).
a = int(input()) ⏎ if a > 0: ⏎ print("musbat") ⏎ elif a < 0: ⏎ print("manfiy") ⏎ else: ⏎ print("nol")
3
What does the nested program print if n = -4 is typed?
musbat emas (not positive)
4
Why is an elif chain better than several separate ifs?
In a chain only the first true block is run; with separate ifs several may run at once.