Python ZeroDivisionError: division by zero
ZeroDivisionError: division by zero
This error appears when you try to divide a number by 0. It is not only /: floor division // and the remainder operator % cannot be done with 0 either. It is rare to have typed 0 directly in the code. Most of the time, the variable you divide by holds 0. Look at the value on the right of the division operator on the line where the error happened.
Cause 1. You took an average of zero items
An average is the sum divided by the count. If the list is empty, len() is 0, so you divide by 0. This often happens when no value matches your condition.
Wrong code
scores = [50, 40, 30]passed = [s for s in scores if s >= 60]print(sum(passed) / len(passed))Traceback (most recent call last): File "main.py", line 3, in <module> ZeroDivisionError: division by zero
Fixed code
Check whether the list is empty before dividing. An empty list counts as false in an if.
scores = [50, 40, 30]passed = [s for s in scores if s >= 60]if passed: print(sum(passed) / len(passed))else: print("none")none
Cause 2. A 0 came in as input
If you read the number you divide by from input, it can be 0.
Wrong code
a, b = map(int, input().split())print(a / b)6 0
Traceback (most recent call last): File "main.py", line 2, in <module> ZeroDivisionError: division by zero
Fixed code
Handle the case where the divisor is 0 first, with an if. Also check what the problem tells you to print when it is 0.
a, b = map(int, input().split())if b == 0: print("cannot divide")else: print(a / b)6 0
cannot divide
Cause 3. range() starts at 0
range(n) counts from 0. If you divide by that value, the error happens right away, on the first pass of the loop. You often run into this when looking for divisors. When it comes from the remainder operator (%), the error message is slightly different: integer modulo by zero.
Wrong code
n = 12for i in range(n): if n % i == 0: print(i)Traceback (most recent call last): File "main.py", line 3, in <module> ZeroDivisionError: integer modulo by zero
Fixed code
Loop from 1 to n: range(1, n + 1).
In Python 3.12, the message depends on the operation: / gives division by zero, // gives integer division or modulo by zero, % gives integer modulo by zero, and a division involving a float gives float division by zero. The meaning and the fix are the same for all of them.
What to check when you see this error
- On the line where the error happened (the number after
line), find the value on the right of/,//or%. - Print that value with
print()above that line to confirm it really is 0. - Trace back where the 0 came from: the
len()of an empty list, arange()that starts at0, a counter that was never increased, or an input value. - Decide with an
ifwhat to do when the value is 0.