View as PDF

COMPUTING AND DIGITAL LITERACY

Functions

Difficulty level: Intermediate

Computing and Digital Literacy

This document was made by AI and there may be mistakes. If a question or answer looks wrong, use the Flag a mistake button to let Brett know so he can fix it.

Overview of the concept

This is how a program reuses the same job, like a button that adds an item to a cart every time you tap it, without rewriting the code. A function is a named chunk of work a program can call whenever it needs it, so the same job is written once and used a hundred times. Every app you use is full of them, from a button that adds to a cart to a search box that filters a list, and knowing how they work is the first step to building anything of your own.

Worked examples

Example 1

You define double(n) to return 2 × n. What does print(double(7)) show?

Solution

def double(n):

return 2 * n

print(double(7)) -> Output: 14

Define the function once: def double(n) names it double and names its input n.

Inside, return 2 * n sends the result back to the caller.

Call it with 7: double(7) works out 2 * 7 = 14 and print shows 14.

Example 2

Using the same double function, what do print(double(3)) and print(double(10)) show?

Solution

print(double(3)) -> 6

print(double(10)) -> 20

Same definition, two different inputs, two answers.

Call double(3): 2 * 3 = 6, so 6 prints.

Call double(10): 2 * 10 = 20, so 20 prints.

Nothing was rewritten: the one definition served both calls.

Practice questions

1

def double(n): return 2 * n. What does double(7) give?

2

def triple(n): return 3 * n. What does triple(4) give?

3

def add_one(n): return n + 1. What does add_one(9) give?

4

def square(n): return n * n. What does square(5) give?

5

def double(n): return 2 * n. What does double(double(3)) give?

6

def double(n): return 2 * n. double(n) gives 20. What is n?

7

def triple(n): return 3 * n. What do print(triple(2)) and print(triple(5)) show?

8

def greet(name): return 'Hello, ' + name. What do print(greet('Ana')) and print(greet('Ben')) show?

9

What is a function?

10

Why use a function instead of copying code?

ANSWER KEY

1. 14

2. 12

3. 10

4. 25

5. 12

6. 10

7. 6 and 15

8. Hello, Ana and Hello, Ben

9. A named block of code that performs one job and can be reused

10. So the job is written once, stays consistent, and is easy to fix