if, elif and else choose which lines run; for and while loops repeat them. Indentation shows which lines belong to each block.
| range(5) | 0, 1, 2, 3, 4 (five values) |
| range(1, 10, 3) | 1, 4, 7 |
| Sum 1 to n | range(1, n + 1), with s starting at 0 |
| Nested loops | range(3) inside range(4): 12 runs |
| A grade chain | if marks >= 90: print('A') elif marks >= 75: print('B') else: print('C') |
| A while loop | n = 20 while n > 5: n = n - 6 print(n) # 2 |
This program should print the first 7 even numbers starting from 2.
for i in range(2, 14, 2):
print(i)
(a) Write the numbers it actually prints. (b) How many numbers is that? (c) What is the smallest stop value for range that prints all 7 numbers?
Working: range stops before its stop value, so it must be more than 14
Answer: (a) 2, 4, 6, 8, 10, 12; (b) 6; (c) 15