ZeroDivisionError: What It Means and How to Fix It
Error reference
ZeroDivisionError
Language
Severity
MediumWhen it happens
A ZeroDivisionError is raised in Python when you attempt to divide a number by zero.
Potential fixes
Always check that the divisor is not zero before dividing. Use a guard (if divisor != 0) or wrap the division in a try/except ZeroDivisionError block. In data processing, decide what the correct fallback value should be (0, None, or a custom sentinel).
Related errors
Deep dive
A ZeroDivisionError is raised in Python when you attempt to divide a number by zero. Division by zero is mathematically undefined, so Python raises this error rather than returning a result.
Why it happens
- •The denominator variable is zero, often due to empty data (e.g. dividing by a count when no items exist).
- •User input that evaluates to zero is passed directly to a division operation.
- •An intermediate calculation produces zero unexpectedly.
- •Using the modulo operator (%) with a zero divisor.
Potential fixes
Always check that the divisor is not zero before dividing. Use a guard (if divisor != 0) or wrap the division in a try/except ZeroDivisionError block. In data processing, decide what the correct fallback value should be (0, None, or a custom sentinel).
Examples
Code that triggers the error
total = 100
count = 0
average = total / count
print(average)Error output
Traceback (most recent call last):
File "app.py", line 3, in <module>
average = total / count
ZeroDivisionError: division by zeroFixed code
total = 100
count = 0
if count != 0:
average = total / count
else:
average = 0 # or None, or raise a custom error
print(average) # 0Practice in English
How would you explain a ZeroDivisionError to a fellow dev? Choose the right phrase:
"I hit an error...
Ready to practice your English at work?
Lingua-e has interactive exercises built around real developer conversations: standups, code reviews, retrospectives, and more. Practice until it comes naturally.
Try Lingua-e for free