Python: choosing and repeating
A condition is True or False. Python compares with == (equal), != (not equal), < > <= >=, and joins conditions with and, or, not. Note that == compares, while a single = stores. The if statement runs its block only when the condition is True; elif gives another condition to try; else runs when none was True. The block is shown by indentation: the lines that belong to the if are pushed in by four spaces after the colon. In the first program, mark = 72 fails mark >= 90, passes mark >= 70, so it prints B. A for loop repeats for each value of a counter: range(1, 5) gives 1, 2, 3, 4 (the end value 5 is not included). The second program adds these four numbers into total and prints 10. A while loop repeats as long as its condition is True; it must change something inside, or it never stops. The third program counts down from 3 and then prints Go. Finally, and joins two conditions: age >= 13 and age < 18 is True only if both parts are True, so for age = 15 it prints True.
1mark = 72 2if mark >= 90: 3 print("A") 4elif mark >= 70: 5 print("B") 6else: 7 print("C")
B
1total = 0 2for i in range(1, 5): 3 total = total + i 4print(total)
10
1n = 3 2while n > 0: 3 print(n) 4 n = n - 1 5print("Go")
3 2 1 Go
1age = 15 2print(age >= 13 and age < 18)
True
On paper, trace this program in a table with columns i and total, then write what it prints: total = 0, for i in range(1, 5): total = total + i * 3, then print(total). Then change the program to count down from 5 with a while loop.