Python error explained
ZeroDivisionError: what it means and how to fix it
You divided by zero, which has no answer.
The message
ZeroDivisionError: division by zero
What it means
Dividing by zero is undefined in maths, so Python stops rather than give a made-up answer. It happens with /, // and %.
Common causes
- Working out an average of an empty list
- A count or total that turned out to be 0
- Percentages where the whole is 0
Example that raises it
def average(nums):
return sum(nums) / len(nums)
print(average([4, 8, 6]))
print(average([]))
The fix
def average(nums):
if not nums:
return 0
return sum(nums) / len(nums)
print(average([4, 8, 6]))
print(average([]))
Tip: Check for the empty case before dividing. An empty list is falsy, so "if not nums" catches it.
Fix the broken version yourself in the editor on this page. It runs real Python in your browser.