Year 9 Computing — Loops that count
Work out what values a counting loop's variable takes, and how many times its body runs.
Name: ________________________
1.Follow this code by hand. How many numbers does it print altogether?
for n in range(2, 7): print(n) print(n * 10)2.This loop takes away rather than adds. What is total at the end?
total = 100 for n in range(1, 4): total = total - n3.Follow this code by hand. How many numbers does it print?
for n in range(3, 9): print(n)4.Look hard at the two numbers in the range. How many times does the indented line run?
for step in range(5, 5): print(step)- a) 0
- b) 10
- c) 5
- d) 1
5.The counter starts a long way above zero here. How many times does the indented line run?
for n in range(10, 20): print(n * 2)6.Each of these loops prints its counter every time round. Match each range to the last number the loop prints.
- range(1, 6)
- range(4, 9)
- range(0, 3)
- range(7, 11)
- range(2, 15)
- 5
- 10
- 2
- 8
- 14
7.Follow this code by hand. What is the last number it prints?
for n in range(1, 5): print(n)8.Follow this code by hand. What is the largest number it prints?
for n in range(6, 11): print(n * 3)
Answer key — Year 9 Computing — Loops that count
- 1. 10
- 2. 94
- 3. 6
- 4. a) 0
- 5. 10
- 6. range(1, 6) → 5; range(4, 9) → 8; range(0, 3) → 2; range(7, 11) → 10; range(2, 15) → 14
- 7. 4
- 8. 30