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

How to debug it

  1. Find the denominator expression in the traceback line and ask: which input makes this zero? Reproduce with exactly that input.
  2. Decide the policy for the empty/zero case: return 0.0, return None, or raise a clear ValueError("no data to average"). There is no universal right answer — but silence is always wrong.
  3. Guard before dividing (if not scores: …) rather than catching ZeroDivisionError after; the guard documents intent.
  4. 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 हो।

पूरी Hindi explanation पढ़ें →

Related errors

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.