问题
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