Sentinan
Sentinan

Reputation: 89

Strange Error: ZeroDivisionError: float division by zero

I found a strange behavior and hope someone has an explanation for it. I'm doing:

if len(list) > 1 and len(list2) > 1:
   total = sum(list) + sum(list2)
   result = percentage(sum(list), total)

def percentage(part, whole):
    return float(part) / float(whole) *100

The two lists are a mix of float and int values. I sporadically get:

ZeroDivisionError: float division by zero

This doesn't makes sense to me. Does anyone have an idea what's happening?

Upvotes: 2

Views: 8729

Answers (2)

Rarblack
Rarblack

Reputation: 4664

Use try/exception:

if len(list) > 1 and len(list2) > 1:
           total = sum(list) + sum(list2)
           result = percentage(sum(list), total)

        def percentage(part,whole):
            while True: 
                try:
                    return float(part) / float(whole) * 100
                except ValueError as e:
                    print(e)

This will not quit the program due to the error, it will just print the error.

Upvotes: 0

hostingutilities.com
hostingutilities.com

Reputation: 9529

The problem is obvious if you print out the values of part and whole that caused this error to occur.

The solution is to handle any Division by Zero errors like so

       try:
           result = percentage(sum(list), total)
       except ZeroDivisionError:
           # Handle the error in whatever way makes sense for your application

Alternatively, you can check for zero before you divide

def percentage(part,whole):
    if whole == 0:
        if part == 0:
            return float("nan")
        return float("inf")
    return float(part) / float(whole) *100

(Thank you Joran Beasley and Max for making this mathematically correct)

Upvotes: 4

Related Questions