错误python:[ZeroDivisionError:除以零]

时间:2015-04-24 01:04:27

标签: python

当我使用python运行程序时遇到错误: 错误是这样的:

ZeroDivisionError: division by zero

我的程序可视化与此类似:

In [55]:

x = 0
y = 0
z = x/y
---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
<ipython-input-55-30b5d8268cca> in <module>()
      1 x = 0
      2 y = 0
----> 3 z = x/y

ZeroDivisionError: division by zero

在这里我想问一下,如何避免python中的错误,我想要的输出是z = 0

1 个答案:

答案 0 :(得分:21)

抓住错误并处理它:

try:
    z = x / y
except ZeroDivisionError:
    z = 0

或者在进行除法之前检查:

if y != 0:
    z = x / y
else:
    z = 0

后者可以简化为:

z = (x / y) if y != 0 else 0