Code

Functions Are Values

In Python a function is an object, just like a number or a list. You can store it in a variable, put it in a dict, pass it to another function, or return it.

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

speak = shout              # no () : the function itself, not a call
print(speak("hello"))      # HELLO!

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

print(twice(shout, "hi"))  # HI!!

A lambda is a one-expression function without a name, handy when you need a small function just once:

add = lambda a, b: a + b   # same as: def add(a, b): return a + b

A dict of functions makes a neat dispatch table, replacing a long if/elif chain:

COMMANDS = {"up": str.upper, "low": str.lower}
print(COMMANDS["up"]("moss"))   # MOSS

And a function can build and return a new function:

def make_adder(n):
    return lambda x: x + n

add5 = make_adder(5)
print(add5(10))             # 15

Assignment

  1. apply_all(value, steps): steps is a list of functions. Apply them in order (each to the previous result) and return the final value.
  2. Fill the OPERATIONS dict so "+", "-" and "*" map to functions of two numbers.
  3. calculate(a, op, b) looks up op in OPERATIONS and returns the result. Unknown operators raise ValueError.
  4. make_multiplier(n) returns a function that multiplies its argument by n.