Skip to content
Codewilds

Lesson 13 of 34 · Functions

Boss: Python Higher-Order Functions

Boss battlehard100 XP1 min read

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": returns value + amount
  • for "multiply": returns value * amount
  • for "cap": returns value, but never more than amount (min(value, amount))
  • for any other kind: returns value unchanged

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)  # 300

Premium 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
Play the 8 free lessons

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 .

Write code ↓
Python+100 XP

Lesson 13 is part of the full course. The first 8 lessons are free.

Premium 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
Play the 8 free lessons

Want more than one course?

The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.