CurriculumWriting Clean Python Code, for KidsSpotting duplication
Spotting Duplicated Code in Python: Exact vs Structural
Some duplication is the same lines repeated. Some is harder to see — the same SHAPE, wearing different names.
Spotting duplication
Three print lines, only the name different each time — that's the easy kind of duplication to spot.
A function with a parameter fixes it directly — write the pattern once, call it as many times as needed.
def greet(name):
print('Hello, ' + name + '!')
greet('Ember')
greet('Blaze')Output
Hello, Ember!
Hello, Blaze!Now a harder case. These two functions LOOK different — different names, different number — but watch their SHAPE.
take_damage_ember and take_damage_blaze do the exact same thing: subtract a number from hp. Only the number differs.
def take_damage_ember(hp):
return hp - 10
def take_damage_blaze(hp):
return hp - 15No two LINES here are identical text — so pattern-matching for exact repeats would miss this entirely. But the SHAPE repeats.
The fix: one function, with the varying number as a parameter instead of hardcoded.
def take_damage(hp, amount):
return hp - amount
print(take_damage(40, 10))
print(take_damage(40, 15))Output
30
25The skill here is recognising STRUCTURE, not just text — two things can be 'the same' even when nothing about them is written identically.
Check your understanding
def take_damage_ember(hp): return hp - 10, and def take_damage_blaze(hp): return hp - 15. Are these two functions duplicated code?
def take_damage_ember(hp):
return hp - 10
def take_damage_blaze(hp):
return hp - 15Why: Yes, this is duplication — just the harder-to-spot kind. Both functions have the identical SHAPE (subtract something from hp), differing only in one hardcoded number. That number belongs as a parameter, collapsing both functions into one: take_damage(hp, amount).
take_damage(hp, amount): return hp - amount, replacing the two ember/blaze functions. What's the real benefit of the ONE combined function?
Why: The real benefit is maintenance, not speed. If take_damage's formula ever needs to change — say, factoring in armor — a single combined function means changing it in exactly one place. Two separate near-duplicate functions mean remembering to update BOTH, which is exactly the kind of drift magic numbers cause too.
What you'll practice
This code greets three dragons with three nearly-identical print lines — only the name changes each time. Extract the repeated pattern into a function, greet(name), and call it three times instead.
More from this topic
Spotting duplication 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 →