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.
What ZeroDivisionError means
ZeroDivisionError: division by zeroDividing 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)whenscoresis 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.
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.
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))