Python ZeroDivisionError — Division by Zero
Fix ZeroDivisionError by validating divisors, computing rates only when the denominator is nonzero, and returning a defined value for empty sets.
Symptoms
- Python raises "ZeroDivisionError: division by zero"
- A rate such as average or percentage fails on an empty dataset
- The error appears only when a count is genuinely zero
Possible causes
- The denominator is computed from data that can be empty or sum to zero
- A metric is calculated before checking for a zero count
- Integer division is used where a guarded floating-point division was intended
Diagnosis steps
Reproduce with the triggering dataset
python -c "print(sum([]) / len([]))"Interpretation
This confirms the empty-dataset path; the denominator comes from len().
Locate the divisor expression
grep -rn "/ len(\|/ count\|/ total" src/Interpretation
Every unguarded division by a computed count is a candidate to fix.
Root cause
Python raises ZeroDivisionError when the right operand of /, //, or % is zero. A zero denominator almost always means the input set is empty or its total is zero, which is a data condition the code failed to handle.
Fix
Guard every computed divisor: return a defined default (0, None, or NaN) when the denominator is zero, or compute with statistics.mean, which raises a clear StatisticsError for empty input.
Risk note
Returning 0 for an undefined rate can be misread as a real zero; document the choice or return None to distinguish it.
Verify the fix
Rerun with an empty dataset and confirm no exception and an expected sentinel value. Add tests for zero and nonzero denominators.
Symptoms
This guide profiles the failure behind “Python ZeroDivisionError — Division by Zero”. It walks through the observable symptoms, a reproducible diagnosis path, the underlying root cause, the concrete fix, and how to verify the change and prevent a regression.
Observed symptoms include:
- Python raises “ZeroDivisionError: division by zero”
- A rate such as average or percentage fails on an empty dataset
- The error appears only when a count is genuinely zero
Reproduce and Diagnose
Reproduce the failure in isolation before changing any code. Work through the checks below in order; each one narrows the search space.
Step 1: Reproduce with the triggering dataset
python -c "print(sum([]) / len([]))"
This confirms the empty-dataset path; the denominator comes from len().
Step 2: Locate the divisor expression
grep -rn "/ len(\|/ count\|/ total" src/
Every unguarded division by a computed count is a candidate to fix.
Likely contributors, in order of frequency:
- The denominator is computed from data that can be empty or sum to zero
- A metric is calculated before checking for a zero count
- Integer division is used where a guarded floating-point division was intended
Root Cause
Python raises ZeroDivisionError when the right operand of /, //, or % is zero. A zero denominator almost always means the input set is empty or its total is zero, which is a data condition the code failed to handle.
The Fix
Guard every computed divisor: return a defined default (0, None, or NaN) when the denominator is zero, or compute with statistics.mean, which raises a clear StatisticsError for empty input.
Watch out: Returning 0 for an undefined rate can be misread as a real zero; document the choice or return None to distinguish it.
def average(values):
n = len(values)
if n == 0:
return None # undefined rate, not 0
return sum(values) / n
print(average([])) # None
print(average([2, 4])) # 3.0
Verify and Prevent
Rerun with an empty dataset and confirm no exception and an expected sentinel value. Add tests for zero and nonzero denominators.
Once verified, add a regression test that reproduces the original symptom so the failure cannot silently return.
This class of failure is usually environmental rather than pure logic, so capture the exact command, the environment variables, and the working directory in your bug report. Reproduce it in the smallest possible script, then widen the scope only once the minimal case is understood. A short written checklist for this failure mode saves hours the next time it appears.