Division or modulo by zero
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.
- 1Explicitly dividing a number by `0`.
- 2A variable used as a divisor has a value of `0` at runtime.
- 3A calculation results in a divisor that is `0` due to floating point inaccuracies or logic.
This error is triggered by attempting to divide a number by the integer literal 0.
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.
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.
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.
result = 10 / 0 # ZeroDivisionError: division by zero
try:
result = numerator / denominator
except ZeroDivisionError:
result = float("inf")def safe_divide(a, b):
return a / b if b != 0 else float("inf")✕ 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.
cpython/Objects/exceptions.c
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev