ZeroDivisionError: division by zero
Error message
division by zero
Quick summary
You attempted to divide a number by zero, which is mathematically undefined.
Why this happens
Dividing by a variable that is zero
Dividing by the length of an empty list or container
Calculating an average without checking for an empty dataset
Minimal example
total = 100
count = 0
average = total / count # ZeroDivisionErrortotal = 100
count = 0
if count != 0:
average = total / count
else:
average = 0Check that count is non-zero before dividing. If count is zero, use a default value instead of dividing.
How to diagnose
Check the divisor's value before dividing
Print the divisor to see if it's zero
Look for calculations involving len() that might be zero
How to fix
Check if the divisor is non-zero before dividing
Use try/except ZeroDivisionError to handle the error
Return a default value (like 0) when the divisor is zero
How to prevent
Always check for zero before division
Guard average calculations with a length check
Related Resources
Related Lessons
- Exceptions
ZeroDivisionError.
Related Practice
- Find Mistake: Division by Zero
Practice finding division errors.