ZeroDivisionError: division by zero is raised when you divide a number by zero (or when the denominator of a division or modulo operation is zero). Mathematically, division by zero is undefined, so Python stops and reports the error instead of returning a value. Here is how to avoid or handle it.
What this error means
Expressions like a / b, a // b, or a % b require a non-zero b. If b is zero, Python raises ZeroDivisionError: division by zero. The same applies when the denominator comes from a variable or expression that evaluates to zero.
Common causes
- Literal zero. Code such as
x / 0orn % 0. - Variable denominator. A variable used as divisor is zero in some cases (e.g. user input, or result of another calculation).
- Expression that becomes zero. e.g.
total / (a - a)orcount / len(items)whenlen(items)is 0.
Example that causes the error
result = 10 / 0 # ZeroDivisionError
a, b = 5, 5
result = 10 / (a - b) # ZeroDivisionError: a - b is 0
Fix 1: check before dividing
Ensure the divisor is not zero before performing division.
divisor = 0
if divisor != 0:
result = 10 / divisor
else:
print("Cannot divide by zero!")
result = None
Fix 2: use try-except
Catch ZeroDivisionError when the divisor can be zero and you want a fallback.
try:
result = 10 / divisor
except ZeroDivisionError:
print("Division by zero is not allowed")
result = None
Fix 3: safe handling of user input or counts
When the divisor comes from input or from something like len(items), validate or guard:
# User input:
s = input("Enter a number to divide by: ")
divisor = float(s) if s else 0
if divisor == 0:
print("Cannot divide by zero!")
else:
result = 10 / divisor
print(f"Result: {result}")
# When dividing by a count:
items = []
avg = sum(items) / len(items) if items else 0 # Avoid 0/0
Next steps: Errors & Exceptions · Operators