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.
Your error
Check these first
- 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.
- Check before dividing.
if count:is false for 0, so you can say what should happen instead. - 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.
total = 10
count = 0
print(total / count)
ZeroDivisionError: division by zero
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.
scores = []
print(sum(scores) / len(scores))
ZeroDivisionError: division by zero
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.
n = 0
print(10 % n)
ZeroDivisionError: integer modulo by zero
n = 0
if n:
print(10 % n)
else:
print("Can't divide by 0")
Can't divide by 0
Still stuck?
- In the traceback,
File "main.py", line 3says where the error happened. In the editor, click that line to go to it. - Go over the basics: Numbers and Math
- Other errors: AttributeError, FileNotFoundError, IndentationError, IndexError, KeyError, ModuleNotFoundError, NameError, RecursionError, SyntaxError, TypeError, UnboundLocalError, ValueError