错误python:[ZeroDivisionError:除以零]

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29836964/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 05:05:11  来源:igfitidea点击:

Error python : [ZeroDivisionError: division by zero]

python

提问by markov zain

I faced an error when I run my program using python: The error is like this:

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

ZeroDivisionError: division by zero

The visualization my program similar like this:

我的程序的可视化类似于这样:

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

In here I want to ask, how to avoid that error in python, my desired output is z = 0

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

采纳答案by kindall

Catch the error and handle it:

捕获错误并处理它:

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

Or check before you do the division:

或者在做除法之前检查:

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

The latter can be reduced to:

后者可以简化为:

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