ZeroDivisionError · Examples
Core Python

ZeroDivisionError Examples

Short, runnable programs that show python zerodivisionerror: division by zero in action. Read the explanation, press Run, then change the code and try your own ideas. New to the topic? Start with the Python ZeroDivisionError: Division by Zero lesson.

1The error message for each operator

The wording changes with the operator, so the message tells you which of /, // or % was involved. The cause is always the same: a zero divisor.

The error message for each operator
total, count = 12, 0

for label, func in [("/", lambda: total / count),
                    ("//", lambda: total // count),
                    ("%", lambda: total % count)]:
    try:
        func()
    except ZeroDivisionError as err:
        print(label, "->", err)
Expected output/ -> division by zero
// -> integer division or modulo by zero
% -> integer modulo by zero

2Guarding a percentage change

Growth figures divide by the old value, which can legitimately be zero for a new product. Decide what the report should say in that case.

Guarding a percentage change
def growth(old_sales, new_sales):
    if old_sales == 0:
        return "n/a (no previous sales)"
    change = (new_sales - old_sales) / old_sales * 100
    return f"{change:.1f}%"

print(growth(200, 250))
print(growth(0, 40))
print(growth(80, 60))
Expected output25.0%
n/a (no previous sales)
-25.0%

3Validate user-supplied numbers

When a value comes from a form or file, check it and report the problem clearly. The calculation then stays simple.

Validate user-supplied numbers
def unit_price(total_cost, quantity):
    if quantity <= 0:
        raise ValueError("quantity must be at least 1")
    return total_cost / quantity

for qty in [4, 0]:
    try:
        print(unit_price(20, qty))
    except ValueError as err:
        print("Invalid:", err)
Expected output5.0
Invalid: quantity must be at least 1

4Zero in a loop: skip and continue

When processing many rows, one zero should not stop the whole run. Catch the error inside the loop and record the problem row.

Zero in a loop: skip and continue
rows = [("north", 500, 5), ("south", 300, 0), ("east", 450, 3)]

for region, revenue, orders in rows:
    try:
        print(region, "average order:", revenue / orders)
    except ZeroDivisionError:
        print(region, "has no orders")
Expected outputnorth average order: 100.0
south has no orders
east average order: 150.0

5Infinity is a value, not an error

math.inf can be used like a number, but dividing by a real zero still raises. Use infinity deliberately, for example as the starting value when searching for a minimum.

Infinity is a value, not an error
import math

prices = [12.5, 9.0, 15.25]
lowest = math.inf
for price in prices:
    if price < lowest:
        lowest = price
print("Lowest:", lowest)
print(5 / math.inf)

try:
    print(5 / 0)
except ZeroDivisionError:
    print("Still an error")
Expected outputLowest: 9.0
0.0
Still an error

Practise next

Python ZeroDivisionError: Division by Zero exercises → Back to the lesson

Python Operators examplesPython Exceptions: try, except, else and finally examplesPython TypeError: What It Means and How to Fix It examplesPython ValueError examples