ZeroDivisionError, what it means and how to fix it

Python raises ZeroDivisionError the moment code divides (or takes a modulo) by zero. The message varies slightly by operation (“division by zero”, “float division by zero”, “integer division or modulo by zero”), but the story is uniform: the denominator was a computed value, counts, lengths, differences, totals, and at runtime it was zero. The bug is rarely the division; it is the unchecked assumption that the denominator could not be zero.

What it looks like

scores = []
average = sum(scores) / len(scores)

Traceback (most recent call last):
  File "main.py", line 2, in <module>
ZeroDivisionError: division by zero

# fixed: decide what an empty average means, then guard
average = sum(scores) / len(scores) if scores else 0

The fix, in order

  1. Find the denominator and print it just before the division. Identify which computed value reached zero: a count, a length, a difference of timestamps, a user-entered quantity.
  2. Trace where that value can legitimately be zero. Empty inputs, a filter that matched nothing, a first run with no data yet. Most real denominators have a lawful zero case the original code did not consider.
  3. Choose the right behavior for zero, do not just suppress it. Sometimes zero should skip the calculation, sometimes return 0, sometimes it signals bad data that should stop the program loudly. The guard should encode that decision.
  4. For averages and rates, compute the count first and branch: rate = hits / total if total else 0.0. For modulo by a variable, the same guard applies; x % n with n equal to zero raises too.
  5. If the zero arrives from user input, validate at entry and report it as an input problem (“quantity cannot be zero”) rather than letting the arithmetic error surface.

If it still happens

If the denominator prints as a tiny float rather than zero (values like 1e-17 from accumulated rounding), the division succeeds but produces an astronomically wrong result instead of an error; that is a numerical-stability issue, solved by rounding, thresholds, or decimal arithmetic, not by the guards above.

Common questions

Why doesn't Python just return infinity, like some languages? For floats, IEEE arithmetic does define infinity, but Python deliberately raises instead, judging a silent infinity more dangerous than a loud error in general-purpose code. Libraries like NumPy follow the IEEE convention and warn rather than raise, which is why the same division behaves differently there.

Does 0 / 0 also raise ZeroDivisionError? Yes. Zero divided by zero raises the same exception rather than returning a NaN; Python treats every division by a zero denominator as an error for integers and floats alike.

Related errors

OverflowError · IndexError · RuntimeError