How to Fix Python ZeroDivisionError: division by zero
In this tutorial, you'll learn about How to Fix Python ZeroDivisionError: division by zero. We cover key concepts, practical examples, and best practices.
The Problem
You run 10 / 0 or 10 // 0 or 10 % 0 and Python raises ZeroDivisionError: division by zero. Any arithmetic operation that divides by zero triggers this error.
Quick Fix
Step 1: Identify the division that fails
Run the offending line in isolation:
python3 -c "result = 10 / 0"
Traceback (most recent call last):
File "<string>", line 1, in <module>
ZeroDivisionError: division by zero
The traceback shows the exact file and line number.
Step 2: Add a divisor check before dividing
Guard every division with a conditional:
dividend = 10
divisor = 0
if divisor != 0:
result = dividend / divisor
else:
result = 0
print("Warning: division by zero avoided")
Step 3: Use a try-except block
Wrap risky divisions in a try-except for clean error handling:
python3 -c "
try:
result = 10 / 0
except ZeroDivisionError:
result = float('inf')
print('Division by zero, returning infinity')
"
Division by zero, returning infinity
Step 4: Validate user input
If the divisor comes from user input, validate before using:
divisor = float(input("Enter divisor: "))
if divisor == 0:
print("Divisor cannot be zero")
else:
print(f"Result: {10 / divisor}")
Alternative Solutions
Use a ternary expression for inline checks
Handle division by zero in a single line:
result = dividend / divisor if divisor != 0 else float('inf')
Use math.isclose for floating-point divisors
Floating-point values close to zero can also cause problems:
import math
divisor = 1e-20
if math.isclose(divisor, 0.0):
result = float('inf')
else:
result = 10.0 / divisor
Common Mistakes to Avoid
Using division in list comprehensions without checking. A comprehension like [100 / x for x in values] crashes if 0 is in values. Use a filter: [100 / x for x in values if x != 0].
Forgetting that integer division can also fail. 10 // 0 raises ZeroDivisionError just like float division. The same guard applies to // and % operators.
Assuming a value is non-zero because it came from user validation. A user might enter 0 for a valid field like "number of items." Always check before using as divisor.
Not handling division by zero in vectorized operations. NumPy arrays return inf or nan instead of raising an error, which can silently corrupt calculations. Check with numpy.isinf() or numpy.isnan().
Pro Tips
Use fractions.Fraction for exact rational arithmetic. The fractions module avoids floating-point division entirely: Fraction(1, 3) never divides by zero.
Use numpy.seterr to control behavior. Configure NumPy to raise, warn, or ignore division by zero in vector operations: numpy.seterr(divide='raise').
Add a decorator to guard all divisions. Create a reusable decorator that wraps your function and returns a default on ZeroDivisionError.
Prevention
- Always check that a denominator is non-zero before using it in division.
- Validate user input or external data before arithmetic operations.
- Use
try-except ZeroDivisionErrorwhen working with unknown or untrusted numeric data.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro