CurriculumWriting Clean Python Code, for KidsThe Dragon's Messy Function
Practice Challenge: Refactoring Messy Python Code
Bad names, a magic number, all in one function — refactor it without changing what it does.
The Dragon's Messy Function
You know three fixes now: real names, named constants, and no duplicated shapes. The challenge combines all three in one messy function.
def c(a, b): with a magic 20 buried inside — it WORKS, but nothing about it explains itself.
def c(a, b):
if a < 20:
return b - 10
return b - 15
print(c(15, 100))Output
90Refactored: real names throughout, the 20 named as LOW_HP_THRESHOLD. Same exact answer.
LOW_HP_THRESHOLD = 20
def apply_damage(current_hp, base_damage):
if current_hp < LOW_HP_THRESHOLD:
return base_damage - 10
return base_damage - 15
print(apply_damage(15, 100))Output
90That'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.
Check your understanding
A function is refactored — renamed, magic numbers replaced with named constants — but its OUTPUT changes for the same inputs. What does that mean?
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.
Which of these counts as a genuine refactor of working code?
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.
What you'll practice
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.
More from this topic
The Dragon's Messy Function is one lesson inside Writing Clean Python Code, for Kids — see the full lesson order and what the whole topic covers.
View the full topic →