ZeroDivisionError
PythonERRORNotableArithmetic ErrorHIGH confidence

Division or modulo by zero

What this means

Raised when the second argument of a division or modulo operation is zero. This is a fundamental rule in mathematics and is enforced by Python.

Why it happens
  1. 1Explicitly dividing a number by `0`.
  2. 2A variable used as a divisor has a value of `0` at runtime.
  3. 3A calculation results in a divisor that is `0` due to floating point inaccuracies or logic.
How to reproduce

This error is triggered by attempting to divide a number by the integer literal 0.

trigger — this will error
trigger — this will error
numerator = 10
denominator = 0
result = numerator / denominator

expected output

Traceback (most recent call last):
  File "<stdin>", line 3, in <module>
ZeroDivisionError: division by zero

Fix 1

Check if the divisor is zero before the operation

WHEN The divisor is a variable that could potentially be zero.

Check if the divisor is zero before the operation
numerator = 10
denominator = 0
if denominator == 0:
    print("Cannot divide by zero.")
else:
    result = numerator / denominator

Why this works

A simple conditional check prevents the division from being attempted if the divisor is zero, avoiding the error.

Fix 2

Use a `try...except` block to handle the error

WHEN A zero divisor is a possibility you want to handle gracefully, for example by returning infinity or a default value.

Use a `try...except` block to handle the error
numerator = 10
denominator = 0
try:
    result = numerator / denominator
except ZeroDivisionError:
    result = float('inf') # A common way to represent this case
print(result)

Why this works

The `try...except` block allows you to catch the `ZeroDivisionError` and define alternative logic, such as setting the result to infinity, `NaN`, or another sentinel value.

Code examples
Triggerpython
result = 10 / 0  # ZeroDivisionError: division by zero
Handle with try/exceptpython
try:
    result = numerator / denominator
except ZeroDivisionError:
    result = float("inf")
Avoid with guardpython
def safe_divide(a, b):
    return a / b if b != 0 else float("inf")
What not to do

Adding a very small number (epsilon) to the divisor to avoid zero

This might avoid the error, but it leads to a very large, potentially inaccurate result that can silently corrupt downstream calculations. It's better to handle the zero-division case explicitly.

Sources
Official documentation ↗

cpython/Objects/exceptions.c

Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev

← All Python errors