ZeroDivisionError
ZeroDivisionError: division by zero
Traceback
Traceback (most recent call last):
File "main.py", line 4, in <module>
percentage(50, 0)
ZeroDivisionError: division by zeroWhat causes this error
The divisor in a division, floor division, or modulo operation was zero. This is undefined mathematically and Python raises an explicit exception.
How to fix it
Check for zero before dividing: `result = a / b if b != 0 else 0`. Use try/except ZeroDivisionError. For data processing, handle edge cases where counts or totals might be zero.
Code that causes this error
def percentage(part, total):
return (part / total) * 100
percentage(50, 0)Fixed code
def percentage(part, total):
if total == 0:
return 0.0
return (part / total) * 100
print(percentage(50, 0)) # 0.0About ZeroDivisionError
This is the standard ZeroDivisionError message that appears when dividing by zero. It applies to all division operators: `/` (true division), `//` (floor division), and `%` (modulo). In Python, division by zero is always an error for integers and floats — unlike IEEE 754 which defines infinity as the result, Python raises an exception.
However, the `float('inf')` and `float('nan')` values are available for explicit use. The `decimal` module has configurable traps for division by zero. In data processing, division by zero often indicates edge cases in computations like averages, percentages, and normalizations where the denominator can legitimately be zero.
Defensive programming with conditional checks (`if divisor != 0`) or try/except blocks is the standard approach.
Common scenarios
Computing averages or percentages where the denominator can be zero
Passing extremely large values to math library functions
Performing calculations that exceed float precision limits
Division operations on user-provided input without validation