Grade 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.A loop is wanted that goes round exactly seven times, with its counter starting at 1. How should its range be written?
- a) range(7, 1)
- b) range(1, 8)
- c) range(0, 7)
- d) range(1, 7)
2.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
- 10
- 14
- 5
3.Put these ranges in order of how many times a loop over each of them would go round, fewest first.
- range(1, 5)
- range(3, 5)
- range(0, 7)
- range(10, 20)
4.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)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(10, 14):
- for n in range(0, 4):
- for n in range(5, 8):
- for n in range(2, 6):
- for n in range(7, 10):
- for n in range(1, 4):
6.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) 10
- b) 1
- c) 5
- d) 0
7.A running total climbs inside this loop. What is total at the end?
total = 0 for n in range(1, 5): total = total + n8.Follow this code by hand. How many numbers does it print altogether?
for n in range(2, 7): print(n) print(n * 10)
Answer key — Grade 8 Computer Science — Loops that count
- 1. b) range(1, 8)
- 2. range(1, 6) → 5; range(4, 9) → 8; range(0, 3) → 2; range(7, 11) → 10; range(2, 15) → 14
- 3. 1. range(3, 5) 2. range(1, 5) 3. range(0, 7) 4. range(10, 20)
- 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. d) 0
- 7. 10
- 8. 10