【问题标题】:Error python : [ZeroDivisionError: division by zero]错误python:[ZeroDivisionError:除以零]
【发布时间】:2022-05-10 05:49:58
【问题描述】:

我在使用 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 的值是多少?对于0/0,任何值都有意义(因为x/y==z 仍然暗示z**y==x),但对于除以0 的任何值,任何值都没有意义(除非你有一个无限整数,并定义infinity*0 == 0) .
  • 如果您遇到除以零的情况,您的逻辑就有错误。

标签: python


【解决方案1】:

捕捉错误并处理它:

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

或在进行除法之前检查:

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

后者可以简化为:

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

或者如果你确定y 是一个数字,这意味着如果非零则它是真实的:

z = (x / y) if y else 0
z = y and (x / y)   # alternate version

【讨论】:

    【解决方案2】:
    # we are dividing until correct data is given
    executed = False
    while not executed:
        try:
            a = float(input('first number --> '))
            b = float(input('second number --> '))
            z = a / b
            print(z)
            executed = True
        except ArithmeticError as arithmeticError:
            print(arithmeticError)
        except ValueError as valueError:
            print(valueError)
        except Exception as exception:
            print(exception)
    

    【讨论】:

      【解决方案3】:

      返回零而不是除以零错误可以通过布尔运算来完成。

      z = y and (x / y)
      

      布尔运算从左到右求值并返回操作数,而不是TrueFalse

      如果y0,则返回值为y。如果y0不同,则执行右边的操作,返回值为x / y

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-03-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-11-23
        相关资源
        最近更新 更多