Programming branching algorithms: the elif statement
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.
A pupil planned the awards for a school sports day: 90 points or more won a gold card, 70 or more silver, 50 or more bronze, and otherwise a certificate for taking part. Because the checks went from the top down, each result got exactly one award.
Programmers, menu planners and service staff check many options in order and pick the matching one.
Make a four-option plan on paper that depends on the day of the week. Write one condition and one action per day.
1m = int(input()) 2if m == 12 or m == 1 or m == 2: 3 print("qish") 4elif m <= 5: 5 print("bahor") 6elif m <= 8: 7 print("yoz") 8else: 9 print("kuz")
yoz
1n = int(input()) 2if n > 0: 3 if n % 2 == 0: 4 print("musbat juft") 5 else: 6 print("musbat toq") 7else: 8 print("musbat emas")
musbat toq
“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”.