Brainlag
  1. Library
  2. Debugging
  3. Python

ZeroDivisionErrorWhat is a ZeroDivisionError?

Python stops with a ZeroDivisionError when you divide by zero. Usually an average of an empty list or a count that can be 0.

Python5 min

What ZeroDivisionError means

Output
ZeroDivisionError: division by zero

Dividing by zero has no answer, so Python refuses rather than guessing. The same goes for // and %. The zero is rarely typed in by hand. It is a value that turned out to be 0 at run time.

The usual causes:

  • An average of nothing. sum(scores) / len(scores) when scores is empty.
  • A count that can be zero. Deaths in a game, items in a basket, people in a group.

How to find it

Go to the line number and find the /, // or %. Whatever is on the right of it was 0. Work out where that value came from, then decide what the answer should be in that case: 0, a message, or a different formula. Guard it with an if before dividing.

Run it: the average of an empty list

Press Run and read the error from the bottom up.

main.py to run
scores = []
average = sum(scores) / len(scores)
print(average)

The K/D ratio that crashes on a perfect game

Each player's kill/death ratio is kills divided by deaths. A player with zero deaths should count as having one death. Fix the loop.

exercise_1.py to run
players = {"Ana": [12, 4], "Ben": [9, 0], "Cleo": [5, 5]}
for name in players:
    kills = players[name][0]
    deaths = players[name][1]
    ratio = kills / deaths
    print(name, round(ratio, 1))

Code editor. Press Control or Command plus Enter to run the code. Tab indents; to move focus out of the editor, press Escape and then Tab.