Editor

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

Broken
scores = []
average = sum(scores) / len(scores)
print(average)
Output
Traceback (most recent call last):
  File "<exec>", line 2, in <module>
ZeroDivisionError: division by zero

The fix

Fixed
scores = []
if scores:
average = sum(scores) / len(scores)
else:
average = 0
print(average)
Output
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.

Try fixing it yourself in the editor

2. A total that is still zero

This raises the error

Broken
done, total = 0, 0
percent = done / total * 100
print(f'{percent:.0f}% complete')
Output
Traceback (most recent call last):
  File "<exec>", line 2, in <module>
ZeroDivisionError: division by zero

The fix

Fixed
done, total = 0, 0
percent = done / total * 100 if total else 0.0
print(f'{percent:.0f}% complete')
Output
0% complete

The conditional expression divides only when total is not zero and uses 0.0 otherwise, so the progress line always prints.

Try fixing it yourself in the editor

3. Modulo by zero with `%`

This raises the error

Broken
def multiples(limit, every):
return [n for n in range(1, limit + 1) if n % every == 0]
print(multiples(10, 3))
print(multiples(10, 0))
Output
[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

Fixed
def multiples(limit, every):
if every == 0:
return []
return [n for n in range(1, limit + 1) if n % every == 0]
print(multiples(10, 3))
print(multiples(10, 0))
Output
[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.

Try fixing it yourself in the editor

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: or x / d if d else 0.
  • Remember that //, % and divmod() divide too.

All Python errors · How to read a traceback · Step through your code