☰ Year plan · Communication Technology

Lists and functions

Week 12 · Chapter 12 Programming (2): lists and functions in Python, with small programs that combine them · 3 lessons
3

Small programs that combine lists and functions

ICT Secondary 1 Term 1, Chapter 12, Lessons 12-4 to 12-5: pp. 168–174
GoalCombine a list, a loop and a function to process many values.
New words
traversal · visiting each item of a list in turncounter · a variable that grows by 1 each time something happenstest (True/False function) · a function that returns True or Falseaverage · the sum divided by the number of items
Explanation

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.

Python
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)
Output
[1, 4, 9, 16]
Worked examples
xsquare(x)squares after
11[1]
24[1, 4]
39[1, 4, 9]
416[1, 4, 9, 16]
The trace of the first program, one row per pass of the loop: x is the item, square(x) the result added to squares.
Python
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)
Output
3
A test function and a counter. passed returns True when the mark is 50 or more; count goes up for 72, 50 and 90 only. The program prints 3.
Python
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]))
Output
6.0
An average function. The loop adds 4 + 8 + 6 = 18, then 18 / 3 = 6.0. The function returns the value, and print shows it.
Class activity

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.

Practice
1
What does the first program print if the list is [2, 3]?
2
What does average([10, 20]) return?
3
In the passed program, how many marks of [60, 49, 50] pass?
4
Why trace a program by hand?