Magic Numbers in Python: A Beginner's Guide to Cleaner Code

What are Magic Numbers?

Have you ever seen code like this?

PYTHON
def calculate_discount(price):
    return price * 0.15
Click to expand and view more

What does 0.15 mean? Is it 15%? A discount? A tax?

Magic numbers are numeric values that appear in code without any explanation. They make code hard to read, maintain, and debug.


Why are Magic Numbers a Problem?

1. Hard to Read

Other developers (or future you) can’t understand what the numbers mean.

2. Hard to Maintain

If you need to change a value, you have to search through the entire codebase.

3. Easy to Make Mistakes

The same number might mean different things in different places.


The Solution: Named Constants

PEP 8 recommends using UPPER_SNAKE_CASE for constants. Additionally, clean code practices recommend replacing magic numbers with named constants for better readability.

Practical Example

❌ Avoid this:

PYTHON
def calculate_discount(price):
    return price * 0.15
Click to expand and view more

✅ Do this instead:

PYTHON
DISCOUNT_RATE = 0.15

def calculate_discount(price):
    return price * DISCOUNT_RATE
Click to expand and view more

Another example:

❌ Avoid this:

PYTHON
# What's 86400? How long is that?
time_seconds = 86400
Click to expand and view more

✅ Do this instead:

PYTHON
SECONDS_IN_DAY = 86400

time_seconds = SECONDS_IN_DAY
Click to expand and view more

The Zen of Python

PEP 20 (The Zen of Python) teaches us:

“Explicit is better than implicit.”

“Readability counts.”

Named constants make code explicit and readable!


When You DON’T Need Constants

Not every number is a “magic number”. These are acceptable:

Example where constants are NOT needed:

PYTHON
# These are fine - the meaning is obvious
for index in range(10):
    print(index)

if len(items) > 0:
    return items[0]

result = value * 2  # Doubling is clear
Click to expand and view more

Conclusion

Replacing magic numbers with named constants is a simple habit that greatly improves your code quality. Your team (and your future self) will thank you!

Remember: Code is read much more often than it’s written. Make it clear.


References

Start searching

Enter keywords to search articles

↑↓
ESC
⌘K Shortcut