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.
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
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.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.
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.