All Python errors
ZeroDivisionError in Python: division by zero
ZeroDivisionError means the number you divide by equals zero. To fix it, check the divisor with if before dividing and decide what the program should do when it is 0.
Code with the error
total = 90
count = 0
print(total / count)
Error message (Python 3.12, last line)
Corrected code
total = 90
count = 0
if count == 0:
print("Nothing to divide")
else:
print(total / count)
Output
Nothing to divide
Common causes
- A counter stayed 0 because the loop added nothing.
- Dividing by the length of an empty list when computing an average.
- The operators // and % with zero on the right.
- A subtraction in the divisor happens to give 0.
Practise in the course
Lesson: Math OperationsFrequently asked questions
Can zero be divided by a number?
Yes. 0 / 5 gives 0.0. Only a zero divisor is forbidden.
Does % also raise this error?
Yes. The remainder of division by zero is undefined too.