Class 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.Each of these loop headings has a single print inside it. Put them in order of how many numbers each one prints, fewest first.
- for n in [4, 9]:
- for n in [5, 5, 5, 5]:
- for n in [1, 2, 3]:
- for n in [2, 4, 6, 8, 10]:
2.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) Nothing at all
- d) There is no way to tell
3.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)4.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)5.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]
- 4
- 3
- 2
- 0
- 1
6.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]
- [7, 8, 9]
- [1, 1, 1, 1]
- [10, 9, 6]
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 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)
Answer key — Class 9 Computer Science — Looping over a list
- 1. 1. for n in [4, 9]: 2. for n in [1, 2, 3]: 3. for n in [5, 5, 5, 5]: 4. for n in [2, 4, 6, 8, 10]:
- 2. a) 0
- 3. 1
- 4. 4
- 5. [11, 2, 14, 3] → 2; [1, 2, 3] → 0; [12, 13, 14, 15] → 4; [30] → 1; [11, 12, 13, 1, 2] → 3
- 6. [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
- 7. 3
- 8. 24