Python errors / ZeroDivisionError

ZeroDivisionError: division by zero

A number was divided by zero, which has no answer. The zero is usually a count or a length that came out empty.

ZeroDivisionError: division by zero

Check these first

  1. Where does the zero come from? Print the number you divide by, just before that line: it's often a count, a length or an input.
  2. Check before dividing. if count: is false for 0, so you can say what should happen instead.
  3. All three divide. /, // and % all fail with 0 on the right.

Causes and fixes

1 Dividing by a count of zero

Check the number you divide by, and decide what the program should do when it's 0.

Broken
total = 10
count = 0
print(total / count)
ZeroDivisionError: division by zero
Fixed
total = 10
count = 0
if count:
    print(total / count)
else:
    print("Nothing to divide by")
Nothing to divide by

2 The average of an empty list

len() of an empty list is 0. Check that the list has items first.

Broken
scores = []
print(sum(scores) / len(scores))
ZeroDivisionError: division by zero
Fixed
scores = []
if scores:
    print(sum(scores) / len(scores))
else:
    print("No scores yet")
No scores yet

3 % or // by zero

The remainder % and whole-number division // divide too, so they need the same check.

Broken
n = 0
print(10 % n)
ZeroDivisionError: integer modulo by zero
Fixed
n = 0
if n:
    print(10 % n)
else:
    print("Can't divide by 0")
Can't divide by 0

Still stuck?