ZeroDivisionError: division by zero
What it means
You divided by a number that was zero at that moment. This covers /, // and %, which is why you may also see float division by zero or integer modulo by zero. The zero usually comes from an empty list, a counter that never went up, or a value that was never set.
1. The average of an empty list
This raises the error
Traceback (most recent call last): File "<exec>", line 2, in <module> ZeroDivisionError: division by zero
The fix
0
len([]) is 0, so the division fails. Checking that the list has items first lets you pick a sensible value for the empty case.
2. A total that is still zero
This raises the error
Traceback (most recent call last): File "<exec>", line 2, in <module> ZeroDivisionError: division by zero
The fix
0% complete
The conditional expression divides only when total is not zero and uses 0.0 otherwise, so the progress line always prints.
3. Modulo by zero with `%`
This raises the error
[3, 6, 9] Traceback (most recent call last): File "<exec>", line 5, in <module> File "<exec>", line 2, in multiples ZeroDivisionError: integer modulo by zero
The fix
[3, 6, 9] []
% divides too, so a zero on its right fails the same way, with the message integer modulo by zero. Guarding against zero up front returns an empty list instead.
When you see this error, check
- Print the number you divide by just before the failing line.
- Check
len()of a list before dividing by it. - Guard with
if divisor:orx / d if d else 0. - Remember that
//,%anddivmod()divide too.
Related errors
All Python errors · How to read a traceback · Step through your code