Small programs that combine lists and functions
Real programs combine the pieces. The pattern is: have a list, walk through it with a for loop, call a function on each item, and collect the results. In the first program, square is applied to each number of [1, 2, 3, 4] and append builds a new list, [1, 4, 9, 16]. In the second, passed(mark) is a test: it returns True or False. The loop uses it inside an if, and a counter adds 1 for each mark that passes, so for [45, 72, 50, 38, 90] the answer is 3 (72, 50 and 90). In the third, average(values) adds the numbers in a loop, then divides by len(values) and returns the result, so average([4, 8, 6]) is 18 ÷ 3 = 6.0, a decimal number because / is used. When a program does not give the answer you expect, trace it by hand: write the variables in a table and update them line by line. This finds most mistakes faster than guessing.
1def square(n): 2 return n * n 3 4numbers = [1, 2, 3, 4] 5squares = [] 6for x in numbers: 7 squares.append(square(x)) 8print(squares)
[1, 4, 9, 16]
| x | square(x) | squares after |
|---|---|---|
| 1 | 1 | [1] |
| 2 | 4 | [1, 4] |
| 3 | 9 | [1, 4, 9] |
| 4 | 16 | [1, 4, 9, 16] |
1def passed(mark): 2 return mark >= 50 3 4marks = [45, 72, 50, 38, 90] 5count = 0 6for m in marks: 7 if passed(m): 8 count = count + 1 9print(count)
3
1def average(values): 2 total = 0 3 for v in values: 4 total = total + v 5 return total / len(values) 6 7print(average([4, 8, 6]))
6.0
Write on paper a program with a function is_even(n) that returns True when n % 2 == 0, a list of six numbers, and a loop that counts how many are even. Trace it with the list 3, 8, 5, 6, 10, 7 and write the printed result.