The dragon explains
The Dragon's Messy Function
The dragon: You know three fixes now: real names, named constants, and no duplicated shapes. The challenge combines all three in one messy function.
The dragon: def c(a, b): with a magic 20 buried inside — it WORKS, but nothing about it explains itself.
example.pyPython 3def c(a, b): if a < 20: return b - 10 return b - 15print(c(15, 100))
Output90The dragon: Refactored: real names throughout, the 20 named as LOW_HP_THRESHOLD. Same exact answer.
example.pyPython 3LOW_HP_THRESHOLD = 20def apply_damage(current_hp, base_damage): if current_hp < LOW_HP_THRESHOLD: return base_damage - 10 return base_damage - 15print(apply_damage(15, 100))
Output90The dragon: That's the whole discipline this topic has been building toward: a real refactor changes NOTHING about what the code does — only how easily a human can follow it.
Quick check
Check your understanding
Say your answer out loud before reading the marked one. Every wrong option is a mistake real beginners make.
Question 1 of 2
A function is refactored — renamed, magic numbers replaced with named constants — but its OUTPUT changes for the same inputs. What does that mean?
- Something went wrong — a real refactor should never change behaviour, only readabilityCorrect
- That's expected — refactoring often fixes small bugs along the way
Why: Something went wrong. The entire point of a refactor is changing HOW code is written without changing WHAT it does — renaming and naming constants should be invisible to anyone just running the program. A behaviour change during a refactor means a real mistake crept in, not an improvement.
Question 2 of 2
Which of these counts as a genuine refactor of working code?
- Renaming variables and extracting a repeated pattern into a function, with identical outputCorrect
- Adding a new feature the code didn't have before
Why: Renaming and extracting duplication, with the output staying exactly the same — that's a refactor. Adding a new feature is real, valuable work too, but it's a DIFFERENT kind of change, and keeping the two separate is exactly what makes each one safer to reason about on its own.
In the game
What you'll practice
Three levels in the game: one guided first try with the shape of the answer already there, then two to solve on your own.
- 1
GuidedYour first try
a = 50, b = 3, c = a * b. Rename these to something real — like gold_per_item, item_count, total_gold — and confirm the printed answer is still 150.
- +2
PracticeTwo more, on your own
This lesson is part of PRO.
PRO is a one-time $49.99 purchase, no subscription, and unlocks this whole topic along with everything else. Topics 1–3 are free, start to finish.
Unlock this lesson with PROStuck three times? The game offers the answer — unasked.