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.

Lesson 4 of 4PROAges 10+
See what PRO unlocks →

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

90

Refactored: 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

90

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.

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?

  • Something went wrong — a real refactor should never change behaviour, only readability
  • 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.

Which of these counts as a genuine refactor of working code?

  • Renaming variables and extracting a repeated pattern into a function, with identical output
  • 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.

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.

Unlock this lesson with PRO →

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 →