Bitpath

Lesson 1 · Unit 08

Functions as values

Pass functions around, write tiny ones, wrap one in another

13 exercisesabout 3 min

What you practise

  • Passing a function to a function, lambda, closures, *args and **kwargs, a first decorator

Try a question from this lesson

Pick one

Look at line 5: the parameter func gets called, so whatever is passed in must be a function. What does this program show?

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

def twice(func, value):
    return func(func(value))

print(twice(shout, "hi"))
Hint

Work from the inside out: the inner call first, then the outer call on its result.

The ideas

Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.

Concept

Functions are values

A function's name without brackets is the function itself. Brackets call it.

So a function can be given a second name, stored in a list, or passed to another function, like any other value. You have done it before: sorted(words, key=len) passes len without calling it.

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

say = shout         # no brackets
print(say("hi"))    # HI!

tools = [shout, len]
print(tools[1]("hi"))  # 2

Concept

A function that makes functions

A function can be defined inside another function, and returned from it.

The inner function remembers the variables of the outer one, even after the outer one has finished. Here each function made by make_adder keeps its own n. This is called a closure.

Python
def make_adder(n):
    def add(x):
        return x + n
    return add

add5 = make_adder(5)
add100 = make_adder(100)
print(add5(1))    # 6
print(add100(1))  # 101

Concept

A first decorator

A decorator takes a function and returns a new function that does something extra around it.

@loud above a def is short for greet = loud(greet). From then on, calling greet really calls the wrapper, and the wrapper calls the original.

Python
def loud(func):
    def wrapper(name):
        return func(name).upper()
    return wrapper

@loud
def greet(name):
    return f"hello {name}"

print(greet("ada"))  # HELLO ADA

9 more exercises in the app

  • 4× type the answer
  • 3× multiple choice
  • 1× fill the blanks
  • 1× order the lines

Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.

One email when Bitpath is ready to try. Nothing else. Privacy