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
| Word | What it means | Example |
|---|---|---|
| Function | A named block of code that does one job. It can take values in and give a value back. | len("cat") |
| Argument | A value you give to a function when you call it. | "cat" in len("cat") |
| Parameter | The name a function uses for the value it is given. | word in def f(word) |
| Statement | One instruction for the computer. | |
| Block | A group of statements that belong together. | |
| Procedure | A sub-routine that does something but gives no value back. | |
| Sub-routine | A named piece of code that you can call. Functions and procedures are sub-routines. | |
| Recursion | A function that calls itself. | |
| Closure | A function that remembers values from where it was made. | |
| First-class function | A function you can keep under a name or pass around like any value. | |
| Higher-order function | A function that takes another function in, or gives one back. | |
| Anonymous function | A function with no name. Python calls it a lambda. | |
| Currying | Turning 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
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
| Part | What it is | Example |
|---|---|---|
| Statement | One instruction | total = 5 + 3 |
| Block | Statements that belong together | The lines inside an if |
| Argument | A value you give when you call | print("hi") |
| Procedure | Does a job, gives nothing back | A sub-routine that prints a receipt |
| Function | Does a job, gives a value back | A 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 questionsIdeas 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
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
| Call | It needs | It gives back |
|---|---|---|
| factorial(3) | factorial(2), then 3 times that answer | 3 x 2 = 6 |
| factorial(2) | factorial(1), then 2 times that answer | 2 x 1 = 2 |
| factorial(1) | factorial(0), then 1 times that answer | 1 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
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
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.
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