☰ 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
2

Functions: write once, use many times

ICT Secondary 1 Term 1, Chapter 12, Lessons 12-4 to 12-5: pp. 168–174
GoalWrite functions with parameters and return values, and tell return from print.
New words
function · a named block of code that can be used many timesparameter / argument · the name in the definition / the value given in the callreturn value · the result a function gives back with returnlocal variable · a variable that exists only inside its function
Explanation

A function is a named block of code that we write once and use many times. In def square(n): the name n is the parameter, a placeholder. When we call square(5), the value 5 is the argument, and n holds 5 while the function runs. The word return gives a result back to the place where the function was called, so square(5) is replaced by 25 and we can use it in a calculation, such as square(3) + 1, which is 10. A function with print but without return only shows something on the screen. It gives back the special value None. Compare r = show(4): the screen shows 16, but r holds None. A variable made inside a function, like tax inside add_tax, is local: it exists only while the function runs, and using it outside gives an error. A function can have several parameters, such as area(width, height), and the arguments are matched in order. Functions make programs shorter and let us test one small piece at a time.

Python
1def square(n):
2    return n * n
3
4print(square(5))
5print(square(3) + 1)
Output
25
10
Worked examples
Python
1def show(n):
2    print(n * n)
3
4r = show(4)
5print(r)
Output
16
None
print and return are different. show(4) prints 16 but gives back None, so r holds None and the last line shows None.
Python
1def add_tax(price):
2    tax = price * 0.1
3    return price + tax
4
5print(add_tax(200))
Output
220.0
A function with a local variable. add_tax(200) makes tax = 20.0 and returns 220.0. The variable tax cannot be used after the call. The result has a decimal point because 200 * 0.1 is a decimal number.
Python
1def area(width, height):
2    return width * height
3
4print(area(4, 3))
Output
12
Two parameters. The arguments are matched in order: width gets 4 and height gets 3, so area(4, 3) is 12.
Class activity

Write on paper a function double(n) that returns n * 2 and a function greet(name) that returns the text "Hello " followed by the name. Write the value of double(7) and of greet("Mina"). Which of your functions could you use inside a calculation, and why?

Practice
1
def square(n): return n * n. What is square(6)?
2
In def area(width, height), which names are parameters? In area(4, 3), which values are arguments?
3
A function has print(n * n) but no return. What does it give back?
4
Why can a local variable not be used outside its function?