Error:Python:type exceptions.ZeroDivisionError

From IPRE Wiki
Jump to: navigation, search

Cause

This error occurred because a number was divided by zero.

Solution

Find the area of code that makes the division, and prevent it from dividing by zero. You could test to see if the denominator is zero before attempting to do the division.

For example, consider the following code:

sum = 0
for number in [2, 6, 1, 5, 3]:
   sum = sum + number
   count = count + 1
average = sum/count

That would work fine, given that list. But what if the list were empty:

sum = 0
for number in []:
   sum = sum + number
   count = count + 1
average = sum/count

Then, count would be zero, and would cause this error. But, we could check to see if it is zero:

sum = 0
for number in [2, 6, 1, 5, 3]:
   sum = sum + number
   count = count + 1
if count == 0:
   average = sum/count
else:
   print "Sorry, can't take the average of zero numbers!"

Then, if the list were empty, the code would not crash.