Easier to read with cream paper, a tint, more contrast or larger text? Choose your colours and text, once, for every page.

Free lesson

OS 4.1 (5 of 6): Functional design

The whole lesson, free. Read it and have a go at the activities. To work the tasks and labs in the real lesson, press Start lab, with no account needed.

50 minutes

A quick check that you are not a bot, then your own lab opens on the interactive lesson.

Already have an account? Sign in

One button, one job

Look at a calculator. The + button adds. The x button multiplies. Each button does one job.

You can use them in any order. You can use the answer of one as the input of the next.

Functional design builds programs in this way: from small parts that each do one job.

Key words

WordWhat it meansExample
FunctionA named block of code that does one job. It can take values in and give a value back.len("cat")
ArgumentA value you give to a function when you call it."cat" in len("cat")
ParameterThe name a function uses for the value it is given.word in def f(word)
StatementOne instruction for the computer.
BlockA group of statements that belong together.
ProcedureA sub-routine that does something but gives no value back.
Sub-routineA named piece of code that you can call. Functions and procedures are sub-routines.
RecursionA function that calls itself.
ClosureA function that remembers values from where it was made.
First-class functionA function you can keep under a name or pass around like any value.
Higher-order functionA function that takes another function in, or gives one back.
Anonymous functionA function with no name. Python calls it a lambda.
CurryingTurning a function of many arguments into a chain of one-argument functions.

The cells students fill in are left blank in this preview.

Modules with a single job

In functional design, the program is a set of modules. Each module does one defined job.

A small module is easy to test. You can reuse it in many places. If something breaks, you know where to look.

A function gives back, a procedure does not

Code: python
def cost(price, count):        # a function: it returns a value
    return price * count


def show_receipt(total):        # a procedure: it only prints
    print("You pay", total)


total = cost(3, 4)
show_receipt(total)

# Change the price and the count.

Make a free account to save your work and track your progress.

The parts of functional design

PartWhat it isExample
StatementOne instructiontotal = 5 + 3
BlockStatements that belong togetherThe lines inside an if
ArgumentA value you give when you callprint("hi")
ProcedureDoes a job, gives nothing backA sub-routine that prints a receipt
FunctionDoes a job, gives a value backA sub-routine that gives back the cost

The cells students fill in are left blank in this preview.

Check: the parts

Have a go

Check: the parts

3 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Ideas from functional programming

Functional programming adds six ideas. Python can do all of them.

They are recursion, first-class functions, higher-order functions, anonymous functions, closures and currying.

Run each example. Change it. Watch what happens.

Recursion: a function calls itself

Code: python
def countdown(n):
    if n == 0:            # the stop rule
        print("Go!")
    else:
        print(n)
        countdown(n - 1)   # the function calls itself


countdown(3)

# Remove the stop rule and see what happens.

Make a free account to save your work and track your progress.

Worked example: factorial

CallIt needsIt gives back
factorial(3)factorial(2), then 3 times that answer3 x 2 = 6
factorial(2)factorial(1), then 2 times that answer2 x 1 = 2
factorial(1)factorial(0), then 1 times that answer1 x 1 = 1
factorial(0)Nothing. This is the stop rule.1

The cells students fill in are left blank in this preview.

Calls go down, answers come up

Note

The calls go down first: 3, 2, 1, 0. The answers come back up: 1, then 1, then 2, then 6. The last call to start is the first to finish.

A function is a value

Code: python
def shout(text):
    return text.upper() + "!"


say = shout              # first-class: keep a function under another name
print(say("hello"))


def apply_to_all(func, items):   # higher-order: it takes a function
    results = []
    for one in items:
        results.append(func(one))
    return results


print(apply_to_all(shout, ["goal", "win"]))
print(apply_to_all(lambda x: x * 2, [1, 2, 3]))   # a lambda: no name

Make a free account to save your work and track your progress.

A closure remembers its values

Code: python
def make_adder(n):
    def add(x):
        return x + n   # add remembers n
    return add


add_five = make_adder(5)
print(add_five(10))

# Currying: one argument at a time.
print(make_adder(2)(3))

Make a free account to save your work and track your progress.

Match the idea

Have a go

Loading…

Your answers are marked here and are not kept. A college account keeps every student’s marks.

Write five small functions

Finish five small functions. Each one uses an idea from this lesson: a higher-order function, a closure, recursion, a lambda and currying. Read the comment in each one. Press Run Tests.

Code: python
def apply_twice(func, value):
    # Use func on value, then use func on the answer.
    return None


def make_multiplier(n):
    # Give back a NEW function. When you call the new function with x,
    # it gives back x times n.  (This is a closure.)
    return None


def factorial(n):
    # 5 factorial is 5 * 4 * 3 * 2 * 1 = 120. 0 factorial is 1.
    # Solve it with recursion: the function calls itself.
    return None


def sort_by_length(words):
    # Give back the words, shortest first. Use sorted() with a lambda as the key.
    return None


def add_curried(a):
    # add_curried(2)(3) must give back 5: one argument at a time.
    return None

Make a free account to save your work, or press Start lab to work through the whole lesson.

Key words crossword

Have a go

Loading…

Your answers are marked here and are not kept. A college account keeps every student’s marks.

Exit quiz

Have a go

Exit quiz

5 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Teach this lesson with your class

On a college account your students work the tasks and the labs as well, and every mark is kept for you.