BugHunt

ZeroDivisionError: division by zero

You divided by something that was 0. Almost always a count or length that turned out to be zero for an input you did not test — usually an empty list.

PythonLogic errors

What it means

Python raises rather than returning infinity for /, // and %. Variants of the message ("float division by zero", "integer modulo by zero") all mean the same thing. The interesting question is never the division — it is why the divisor was zero, and whether that case was ever meant to be possible.

Common causes

1. Averaging an empty list

len([]) is 0. Every average function needs an answer for "no data".

Breaks

def average(nums):
    return sum(nums) / len(nums)

Works

def average(nums):
    if not nums:
        return 0
    return sum(nums) / len(nums)

2. A percentage of a total that can be zero

Works for every real report until the first one with no rows.

Breaks

rate = passed / total * 100

Works

rate = passed / total * 100 if total else 0.0

3. A loop counter that is never incremented

The count stays at its initial 0 because the increment is in the wrong branch.

Breaks

count = 0
for x in data:
    if x > 0:
        total += x
print(total / count)

Works

count = 0
for x in data:
    if x > 0:
        total += x
        count += 1

How to find it in your own code

Decide what the answer should be when the divisor is zero — 0, None, or an error the caller must handle — and write that case first, as a guard at the top of the function. A guard is clearer than wrapping the division in try/except.

Try it: fix this bug

hard

safe_ratio(1, 0) raises ZeroDivisionError instead of returning False, even though the code checks b != 0.

def safe_ratio(a, b):
    if a / b > 1 and b != 0:
        return True
    return False
Open with hintsRuns in your browser. No account needed.

Still not sure why yours breaks?

Paste it into the visualizer and watch it run line by line, with every variable at every step. Free, and it runs in your browser.

Other common errors