我发现了一个奇怪的行为,希望有人能对此做出解释。我正在做:
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
这两个列表是 float 和 int 值的混合。我偶尔会得到:
ZeroDivisionError:浮点数除以零
这对我来说没有意义。有人知道发生了什么事吗?
如果你打印出以下值,问题就很明显了part
and whole
导致了这个错误的发生。
解决方案是像这样处理任何除零错误
try:
result = percentage(sum(list), total)
except ZeroDivisionError:
# Handle the error in whatever way makes sense for your application
或者,您可以在除法之前检查零
def percentage(part,whole):
if whole == 0:
if part == 0:
return float("nan")
return float("inf")
return float(part) / float(whole) *100
(感谢 Joran Beasley 和 Max 使这个数学正确)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)