Strange Error: ZeroDivisionError: float division by zero

无人久伴 提交于 2021-02-08 02:32:23

问题


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?


回答1:


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)




回答2:


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.



来源:https://stackoverflow.com/questions/53123918/strange-error-zerodivisionerror-float-division-by-zero

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!