Year 10 Computing — 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. Sort each list by the total the loop leaves behind.
values = [6, 6] total = 0 for n in values: total = total + nGroups: A total of more than 20 · A total of less than 20
- [5, 5, 5]
- [4, 3, 2]
- [12, 11]
- [10, 9, 6]
- [7, 8, 9]
- [1, 1, 1, 1]
2.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)3.The list this loop is given has nothing in it at all. What does the program print?
readings = [] total = 0 for r in readings: total = total + r print(total)- a) 0
- b) 1
- c) There is no way to tell
- d) Nothing at all
4.A running total is built up from a list here. What does this program print?
marks = [4, 7, 2, 5] total = 0 for m in marks: total = total + m print(total)5.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)6.Two counters are kept at once here, and the last line compares them. What does the program print?
marks = [7, 3, 9, 2, 6] passes = 0 fails = 0 for m in marks: if m > 5: passes = passes + 1 else: fails = fails + 1 print(passes - fails)7.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)8.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) 17
- b) 21
- c) 105
- d) 25
Answer key — Year 10 Computing — Looping over a list
- 1. [4, 3, 2] → A total of less than 20; [10, 9, 6] → A total of more than 20; [1, 1, 1, 1] → A total of less than 20; [7, 8, 9] → A total of more than 20; [5, 5, 5] → A total of less than 20; [12, 11] → A total of more than 20
- 2. 24
- 3. a) 0
- 4. 18
- 5. 15
- 6. 1
- 7. 3
- 8. d) 25