我需要计算获胜率的百分比,但我遇到了 ZeroDivisionError 问题:当分母为零时 float 除以零。我想将其视为异常,打印零并继续下一个数组。任何援助将不胜感激。
YearWinLose1 = '0'
YearWinLoseTotalHard2 = '0'
YearWinLoseTotalHard2 = float(YearWinLose1) + float(YearWinLose1)
YearWinLosePercent3 = float(YearWinLose1)/float(YearWinLoseTotalHard2)*100
if YearWinLoseTotalHard2 == 0:
YearWinLosePercent3 == 0
print YearWinLosePercent3
else:
print YearWinLosePercent3
请您参考如下方法:
你可以使用 try/except:
try:
YearWinLosePercent3 = float(YearWinLose1)/float(YearWinLoseTotalHard2)*100
except ZeroDivisionError:
print '0' #or whatever
编辑 1:
为了更正您所写的内容,让我发表一些评论。 通过这一行:
if YearWinLoseTotalHard2 == 0:
错误已经发生在上一行。如果你想使用 if 结构作为控制方法,你应该在 if block 中添加除法:
if YearWinLoseTotalHard2 != 0:
YearWinLosePercent3 = float(YearWinLose1)/float(YearWinLoseTotalHard2)*100
else:
print '0'
还有,你写了
YearWinLosePercent3 == 0
如果您尝试为变量赋值,您应该知道运算符是“=”,而不是“==”。后者用于比较值。
