Lesson 13 of 34 · Functions
Boss: Python Higher-Order Functions
Hissandra the Hydra blocks the way. Every test you pass deals damage — pass them all to defeat it and claim a loot chest.
Hissandra the Hydra blocks the bridge out of the Functions chapter. Cut off one head and two more grow back — unless your attacks are built from small functions that combine cleanly, each one shaping the damage of the next.
Battle plan
You'll need closures and lambdas from the scope lesson, *args and keyword-only parameters from the arguments lesson, and the habit of returning functions instead of calling them. A modifier is simply a function that takes a damage value and returns a new damage value:
plus_five = make_modifier("add", 5)
plus_five(10) # 15
Assignment
Write three functions.
1. make_modifier(kind, amount) returns a modifier function that takes one number value and:
- for
"add": returnsvalue + amount - for
"multiply": returnsvalue * amount - for
"cap": returnsvalue, but never more thanamount(min(value, amount)) - for any other kind: returns
valueunchanged
2. chain(*modifiers) returns a single function that takes a value and passes it through every modifier in order, left to right: the result of the first becomes the input of the second, and so on. With no modifiers, the returned function gives back its input unchanged.
3. attack(base, *modifiers, critical=False) applies all modifiers to base in order. If the keyword-only argument critical is True, it doubles the result after all modifiers have been applied. It returns the final damage rounded to a whole number with round().
add5 = make_modifier("add", 5)
double = make_modifier("multiply", 2)
chain(add5, double)(10) # 30 -> (10 + 5) * 2
chain(double, add5)(10) # 25 -> 10 * 2 + 5
attack(10, add5, double) # 30
attack(10, double, critical=True) # 40
attack(100, double, make_modifier("cap", 150), critical=True) # 300Premium lesson
Unlock the full Learn Python course
- All 34 lessons, bosses and quizzes — lifetime access
- One payment of $35, no subscription
- Finish within 30 days and claim $10.50 (30%) back
Want more than one course?
The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.
Keep learning
Need a quick reminder? The Python cheat sheet has every topic of Learn Python on one page.
Lesson last updated on .