
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
apply_all(value, steps):stepsis a list of functions. Apply them in order (each to the previous result) and return the final value.- Fill the
OPERATIONSdict so"+","-"and"*"map to functions of two numbers. calculate(a, op, b)looks upopinOPERATIONSand returns the result. Unknown operators raiseValueError.make_multiplier(n)returns a function that multiplies its argument byn.
apply_all(value, steps):stepsis a list of functions. Apply them in order (each to the previous result) and return the final value.- Fill the
OPERATIONSdict so"+","-"and"*"map to functions of two numbers. calculate(a, op, b)looks upopinOPERATIONSand returns the result. Unknown operators raiseValueError.make_multiplier(n)returns a function that multiplies its argument byn.
main.py Python sleeping
Press Run to try your code, then Check to test it.