ArithmeticPython Error

ZeroDivisionError

ZeroDivisionError: division by zero

Traceback

terminal
Traceback (most recent call last):
  File "main.py", line 4, in <module>
    percentage(50, 0)
ZeroDivisionError: division by zero

What 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

Broken
def percentage(part, total):
    return (part / total) * 100

percentage(50, 0)

Fixed code

Fixed
def percentage(part, total):
    if total == 0:
        return 0.0
    return (part / total) * 100

print(percentage(50, 0))  # 0.0

About 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

1

Computing averages or percentages where the denominator can be zero

2

Passing extremely large values to math library functions

3

Performing calculations that exceed float precision limits

4

Division operations on user-provided input without validation

Related errors