Practical lesson: the if…else statement
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.
For a yard game, teams had to be split evenly: if the number of players is even, make two teams; if odd, one person is the referee. This is an even-odd check done with the remainder.
Organisers, referees and programmers check a remainder to share work into groups.
Write five numbers and divide each by 2 on paper to mark even or odd. Then find those divisible by 3.
1a = int(input()) 2b = int(input()) 3if a % b == 0: 4 print("ha") 5else: 6 print("yo‘q", a % b) 7 8a = int(input()) 9b = int(input()) 10if a > b: 11 m = a 12else: 13 m = b 14print(m)
yo‘q 2 15
1t = int(input()) 2if t >= 25: 3 print("issiq") 4else: 5 print("salqin") 6 7x = int(input()) 8if x < 0: 9 x = -x 10print(x)
issiq 9
“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.
1a = 12 2b = 5 3if a % b == 0: 4 print(a // b) 5else: 6 print(a % b)