Programming branching algorithms: the if…else statement
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.
At break the pupil on duty followed one rule: if it is raining, send the classes to the hall; otherwise send them to the yard. Every break got exactly one of the two actions, which is the if…else idea.
Programmers, data-entry staff and accountants choose between two actions depending on a condition.
Write one two-branch rule from your day as Python-style lines on paper: a line with if … and a colon, an indented action, then else with a colon and another indented action. Check the colons and indents by eye.
1n = int(input()) 2if n > 0: 3 print("musbat") 4else: 5 print("musbat emas")
musbat emas
1n = int(input()) 2if n % 2 == 0: 3 print("juft") 4else: 5 print("toq") 6 7s = int(input()) 8if s >= 100000: 9 s = s - s // 10 10print(s)
toq 135000
“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.
1x = 4 2if x % 2 == 0: 3 y = x // 2 4else: 5 y = 3 * x + 1