ZeroDivisionError
This error occurs when you attempt to divide a number by zero or perform a modulo operation with a divisor of zero.
Usually happens because:
- ☑ Denominator variable in division (/) evaluates to zero
- ☑ Divisor variable in modulo (%) evaluates to zero
- ☑ Dividing totals by len(items) when the items list is empty
🔍 Quick Checklist:
What is ZeroDivisionError?
A 'ZeroDivisionError' is raised at runtime when the second argument of a division or modulo operator is zero. Mathematically, division by zero is undefined, and Python raises this exception to prevent incorrect arithmetic cascades. This commonly occurs when computing averages, processing ratio fractions, or during statistical database queries containing empty datasets.
Common Causes
- Division by zero: Using the slash (/) or double-slash (//) operator with a denominator of zero.
- Modulo by zero: Using the modulo (%) operator with a divisor of zero.
- Calculating averages on empty lists: Dividing a sum by 'len(items)' when the list is empty.
| Cause | Frequency |
|---|---|
| Dividing totals by zero denominator variable | ⭐⭐⭐⭐⭐ |
| Calculating averages on empty lists (len == 0) | ⭐⭐⭐⭐ |
| Modulo operations with a zero divisor | ⭐⭐⭐ |
Common Mistakes
- Assuming modulo operators (`%`) with a zero divisor return 0 or do not raise division errors.
- Using float conversions on denominators (e.g. `10 / 0.0`) expecting it to return infinity (`inf`) like other languages (Python raises a ZeroDivisionError for floating-point zero divisions as well).
How to Fix
Python Operations & Verification
Ensure the list contains elements prior to dividing total sums by sequence length.
def calculate_average(prices):
# Protect against empty lists to avoid ZeroDivisionError
if not prices:
return 0.0
return sum(prices) / len(prices)Platform Specific Fixes
Verify division behaviors in python interactive prompts.
python3 -c "print(5 / 0 if 0 != 0 else 'Safe')"Best Practices
- Verify the size of input datasets before calculating metrics aggregates.
- Establish default fallback values in configuration files for denominator fields.
Frequently Asked Questions (FAQ)
Q: What is a ZeroDivisionError?
It is a runtime exception raised when the denominator in a division or modulo operation is zero.
Q: How do I prevent ZeroDivisionError?
Always validate your divisor before running a division command: 'result = numerator / divisor if divisor != 0 else 0'.
Q: Why does modulo (%) by zero raise this error?
Modulo calculates the remainder of a division. Because division by zero is undefined, calculating a remainder when dividing by zero is also impossible and raises this exception.
Q: How do I calculate list average safely?
Verify the list is not empty first: 'avg = sum(items) / len(items) if items else 0'.