CurriculumWriting Clean Python Code, for KidsMagic numbers and named constants
Python Magic Numbers and Why Named Constants Fix Real Bugs
A bare number with no stated meaning is a bug waiting to happen the moment it needs to change.
Magic numbers and named constants
health < 20 works fine — but why 20? Nothing about the bare number says. That's called a MAGIC NUMBER.
Naming it fixes that instantly: LOW_HEALTH_THRESHOLD = 20 puts the meaning right where the value is declared.
LOW_HEALTH_THRESHOLD = 20
health = 15
if health < LOW_HEALTH_THRESHOLD:
print('Low health warning!')Output
Low health warning!This isn't just about readability — magic numbers cause a REAL bug when the same value has to appear more than once.
Two checks, SUPPOSED to use the same threshold — but someone updated one bare number and forgot the other.
health = 25
if health < 30:
print('Low health warning!')
if health < 20:
print('Healing needed!')Output
Low health warning!Only the warning fires. The healing check is silently using an OLD threshold, because it was never actually connected to the first one — they just happened to match once.
A named constant makes that impossible: change LOW_HEALTH_THRESHOLD once, and every use of the NAME updates together, because there's only one real value to change.
LOW_HEALTH_THRESHOLD = 30
health = 25
if health < LOW_HEALTH_THRESHOLD:
print('Low health warning!')
if health < LOW_HEALTH_THRESHOLD:
print('Healing needed!')Output
Low health warning!
Healing needed!Check your understanding
A magic number appears in TWO places in a program, both meant to represent the same threshold. What's the real risk?
Why: The real risk is silent disagreement — nothing connects two bare literals that happen to share a value, so updating one and forgetting the other produces code that runs fine but behaves inconsistently. A named constant used in both places makes that structurally impossible, since there's only one real value to change.
LOW_HEALTH_THRESHOLD = 30, used in two different if checks. If you change the 30 to 25, what happens to BOTH checks?
LOW_HEALTH_THRESHOLD = 25
if health < LOW_HEALTH_THRESHOLD:
...
if health < LOW_HEALTH_THRESHOLD:
...Why: Both checks update together — that's the whole point. They're both reading the same NAME, not two independent numbers that happen to currently match, so changing the one place the value is defined changes every use of it at once.
What you'll practice
health = 15, and the warning fires when health < 20 — but nothing about the bare number 20 says WHY that's the threshold. Replace it with a named constant, LOW_HEALTH_THRESHOLD = 20, and use the name in the comparison instead of the bare number.
More from this topic
Magic numbers and named constants 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 →