ZeroDivisionError
ZeroDivisionError: division by zero
Traceback
Traceback (most recent call last):
File "main.py", line 1, in <module>
average = total / count # count is 0
ZeroDivisionError: division by zeroWhat causes this error
The denominator in a division, floor division, or modulo operation is zero. Python does not allow division by zero for integers or floats.
How to fix it
Check that the denominator is not zero before dividing. Use a conditional or try/except block. For numeric computing with numpy, use `np.divide()` with appropriate handling of infinity values.
Code that causes this error
average = total / count # count is 0
Fixed code
average = total / count if count != 0 else 0
About ZeroDivisionError
A ZeroDivisionError is raised when the second argument of a division or modulo operation is zero. This applies to the `/` (true division), `//` (floor division), and `%` (modulo) operators, as well as the built-in `divmod()` function. The error also applies to integer, float, and decimal operations, though the behavior can differ: `float('inf') / 0` raises ZeroDivisionError but `1.0 / float('inf')` returns 0.0.
In mathematical terms, division by zero is undefined, and Python correctly raises an exception rather than returning a special value. This error frequently appears in calculations involving averages, ratios, and normalizations where the denominator might be zero. The fix is always to check the denominator before dividing, or to use a try/except block.
In data science code, `numpy` handles division by zero differently — it returns `inf` or `nan` with a runtime warning rather than raising an exception.
Common scenarios
Computing averages or percentages where the denominator can be zero
Passing extremely large values to math library functions
Performing calculations that exceed float precision limits
Division operations on user-provided input without validation