ZeroDivisionError
Python Programming Language
Severity: MinorWhat Does This Error Mean?
A ZeroDivisionError means your code tried to divide a number by zero. Division by zero is mathematically undefined — there is no valid answer — so Python raises an error instead of returning a nonsense result. This usually happens when a variable that should hold a non-zero value ends up being zero, often due to unexpected input or logic.
Affected Models
- Python 2.x
- Python 3.x
- All Python versions
Common Causes
- Directly writing something like x = 10 / 0 in your code
- A variable used as a divisor ends up being zero because of user input or a calculation result
- Dividing by a count or total that is zero because a list or dataset is empty
- Using the modulo operator (%) with zero as the divisor (10 % 0 also raises this error)
- A calculation that produces zero as an intermediate result, which is then used as a divisor
How to Fix It
-
Find the division in your code that caused the error. The error message shows the line number.
Look for a / or % operator on that line.
-
Add a check before the division: if denominator != 0: then do the division. Otherwise, handle the zero case separately.
Example: result = numerator / denominator if denominator != 0 else 0
-
If the divisor comes from user input, validate it before using it. Tell the user to enter a non-zero number.
Always assume user input might be zero or invalid.
-
If you are calculating an average of a list, check that the list is not empty before dividing by its length.
Example: average = sum(items) / len(items) if items else 0
-
Use a try/except block to catch ZeroDivisionError if it is expected to occasionally happen and you want to handle it gracefully.
Example: try: result = a / b except ZeroDivisionError: result = 0
When to Call a Professional
ZeroDivisionErrors are always something you can fix yourself. The fix is simply to check that the divisor is not zero before dividing. Think about whether zero is a valid value in your context and handle it with a meaningful result.
Frequently Asked Questions
What does Python return if I divide a float by zero?
If you divide a float by zero in Python, you also get a ZeroDivisionError. This is different from some other languages where float division by zero returns 'Infinity'. Python is strict — it raises an error either way.
What about 0 divided by 0?
That also raises a ZeroDivisionError in Python. Mathematically, 0/0 is 'indeterminate' (not just undefined), but Python treats it the same as any division by zero. The error message says 'division by zero' in both cases.
Should I always use try/except for division?
Not always — it depends on your code. If zero is never a valid divisor, it is better to validate the value and raise a clear error message than to silently return 0. Use try/except when zero is a legitimate edge case that you want to handle without crashing. Use if-checks when zero means bad input that should be rejected.