Class 8 Computer Science — Loops that count
Work out what values a counting loop's variable takes, and how many times its body runs.
Name: ________________________
1.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)
- 2
- 8
- 5
- 14
- 10
2.Follow this code by hand. What is product at the end?
product = 1 for n in range(1, 5): product = product * n3.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) 1
- b) 10
- c) 0
- d) 5
4.Follow this code by hand. How many numbers does it print altogether?
for n in range(2, 7): print(n) print(n * 10)5.Sort each of these loop headings by how many times the body underneath it would run.
Groups: Three times · Four times
- for n in range(7, 10):
- for n in range(0, 4):
- for n in range(5, 8):
- for n in range(2, 6):
- for n in range(1, 4):
- for n in range(10, 14):
6.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)7.This loop takes away rather than adds. What is total at the end?
total = 100 for n in range(1, 4): total = total - n8.A running total climbs inside this loop. What is total at the end?
total = 0 for n in range(1, 5): total = total + n
Answer key — Class 8 Computer Science — Loops that count
- 1. range(1, 6) → 5; range(4, 9) → 8; range(0, 3) → 2; range(7, 11) → 10; range(2, 15) → 14
- 2. 24
- 3. c) 0
- 4. 10
- 5. for n in range(1, 4): → Three times; for n in range(0, 4): → Four times; for n in range(5, 8): → Three times; for n in range(2, 6): → Four times; for n in range(7, 10): → Three times; for n in range(10, 14): → Four times
- 6. 10
- 7. 94
- 8. 10