Home › Errors › ZeroDivisionError
Python ZeroDivisionError: division by zero
Exception: ZeroDivisionErrorCategory: arithmeticRaised at: runtime
What this error means
The right-hand side of /, //, or % evaluated to zero. Division by zero has no defined result, so Python stops immediately. The operator variant changes only the wording: division by zero for /, integer division or modulo by zero for // and %.
Here is the practical insight: in real programs the zero is almost never a literal 0 someone typed. It is a computed zero — len() of an empty list, a count that never incremented, a sum of an empty column. ZeroDivisionError is therefore usually a missing-data bug wearing an arithmetic costume.
A real example
def average(scores):
return sum(scores) / len(scores)
print(average([])) # a new student with no scores yet
Traceback (most recent call last):
File "app.py", line 4, in <module>
print(average([]))
File "app.py", line 2, in average
return sum(scores) / len(scores)
~~~~~~~~~~~~^~~~~~~~~~~~~
ZeroDivisionError: division by zero
The arithmetic is correct; the function simply has no answer for "the average of nothing" — and it must say what happens in that case, explicitly.
Why it happens
- Averaging an empty collection —
sum(x)/len(x)where a filter, file, or new user produced zero items. - A derived collection went empty — the input was checked, but the filtered version wasn't; every filter can reject everything.
- A counter that never counted — dividing by an accumulator that stayed at 0 because a condition never triggered.
- Percentage of a zero total —
part / total * 100the day total is zero.
How to debug it
- Find the denominator expression in the traceback line and ask: which input makes this zero? Reproduce with exactly that input.
- Decide the policy for the empty/zero case: return
0.0, returnNone, or raise a clearValueError("no data to average"). There is no universal right answer — but silence is always wrong. - Guard before dividing (
if not scores: …) rather than catching ZeroDivisionError after; the guard documents intent. - Guard the exact collection being aggregated — a non-empty input list proves nothing about its filtered descendant.
Fix it interactively
Practice more Python bugs →🇮🇳 Hindi में समझें
Zero से divide हुआ — पर असली programs में यह zero कोई टाइप नहीं करता, वह बनता है: खाली list का len(), कभी न बढ़ा counter। इसलिए असली सवाल है: data खाली क्यों था? Divide से पहले if not marks: check लगाओ और खुद decide करो कि empty case में क्या return हो।
Related errors
- ValueError — the input-validation stage where a zero denominator should often be rejected.
- IndexError — the other classic empty-collection crash — items[0] on nothing.
Float oddity worth knowing: 0.0 / 0.0 also raises, but NumPy returns nan with a warning instead — behaviour differs by library. More in the errors guide.