ZeroDivisionError: division 通过零
错误信息
division 通过零
快速摘要
你 attempted 到划分数字通过零, 哪个是 mathematically undefined.
为什么发生
划分通过变量那个是 零
划分通过长度的 空列表 or 容器
Calculating 平均不使用检查 for 空 dataset
最小示例
✗ 错误代码
total = 100
count = 0
average = total / count # ZeroDivisionError✓ 修复代码
total = 100
count = 0
if count != 0:
average = total / count
else:
average = 0检查那个数量是 非-零之前划分. 如果数量是 零, use 默认值 相反的 划分.
如何诊断
检查 divisor's 值之前划分
Print divisor 到 see 如果它's 零
Look for calculations involving len() 那个可能是 零
如何修复
检查如果 divisor 是非-零之前划分
Use try/except ZeroDivisionError 到 handle 错误
返回默认值 (如 0) 当 divisor 是零
如何预防
总是检查 for 零之前 division
Guard 平均 calculations 使用长度检查