Fix: ZeroDivisionError: division by zero
Exact message
ZeroDivisionError: division by zero
Quick answer
ZeroDivisionError occurs when you divide by a number that evaluates to zero. Guard the divisor with an if check, or wrap the division in try/except, or use math.isclose to treat near-zero values as zero.
Why this error happens
Python raises ZeroDivisionError whenever the denominator of /, //, or % is zero. Unlike some languages that return inf or NaN, Python raises because silent inf propagates and creates harder-to-find bugs downstream.
Example: Wrong vs Right
Wrong
total = 100 count = 0 avg = total / count # ZeroDivisionError: division by zero
Right
total = 100
count = 0
avg = total / count if count else 0
# Or raise a clearer error
def safe_div(a, b):
if b == 0:
raise ValueError("Cannot divide by zero")
return a / bHow to fix it (step by step)
- Trace back to find where the zero divisor came from
- Guard the division with 'if divisor != 0'
- Decide what the result should be when the divisor is zero (0, None, exception, or inf)
- For floats, use math.isclose(divisor, 0.0) to treat near-zero values the same
Frequently asked questions
What is the difference between /, //, and %?
All three raise ZeroDivisionError with a zero divisor. / is true division, // floor division, % modulo. None returns inf silently.
Can I make it return inf like NumPy?
Use numpy.divide with errstate ignored, or add a small epsilon. Python's built-in numbers never silently return inf — this is deliberate.
What about modulo by zero?
Same error. 5 % 0 raises ZeroDivisionError. Common in hashing and cyclic-index code — guard with if n:
Related Python errors
Need a fix for a different error?
Use the free to paste any traceback and get an AI-suggested fix in seconds.
Want an AI with memory for your project?
MonsterX AI remembers your codebase across chats.