Grade 9 Computer Science — Looping over a list
Follow a loop that takes each value of a list in turn, and work out the total, the count or the largest value it leaves behind.
Name: ________________________
1.The program below is run again with each of these lists written into its first line. Match each list to the number the loop counts.
values = [4, 5] count = 0 for n in values: if n > 10: count = count + 1- [11, 2, 14, 3]
- [1, 2, 3]
- [12, 13, 14, 15]
- [30]
- [11, 12, 13, 1, 2]
- 3
- 0
- 2
- 4
- 1
2.This one keeps hold of the smallest value instead, and so it starts from something large. What does it print?
times = [34, 28, 41, 30] best = 100 for t in times: if t < best: best = t print(best)3.This one multiplies rather than adds, so what it starts from matters. What does it print?
sizes = [2, 3, 4] product = 1 for s in sizes: product = product * s print(product)4.Every value in this list has ten added to it before printing. What is the last number the program prints?
nums = [6, 1, 8, 5] for n in nums: print(n + 10)5.How many numbers does this program print?
values = [11, 4, 9] for v in values: print(v * 2)6.One line of this program is inside the loop and one is outside it. How many numbers does it print altogether?
prices = [3, 6, 2] total = 0 for p in prices: total = total + p print(p) print(total)7.This loop keeps hold of the largest value it has met so far. What does it print?
temps = [17, 23, 19, 25, 21] best = 0 for t in temps: if t > best: best = t print(best)- a) 21
- b) 105
- c) 25
- d) 17
8.This loop does not add the values up. It counts how many of them pass a test. What does it print?
scores = [3, 8, 2, 9, 6] count = 0 for s in scores: if s > 5: count = count + 1 print(count)
Answer key — Grade 9 Computer Science — Looping over a list
- 1. [11, 2, 14, 3] → 2; [1, 2, 3] → 0; [12, 13, 14, 15] → 4; [30] → 1; [11, 12, 13, 1, 2] → 3
- 2. 28
- 3. 24
- 4. 15
- 5. 3
- 6. 4
- 7. c) 25
- 8. 3