即使使用 try 和 except 后也会出现 ZeroDivisionError

# program to print the reciprocal of even numbers


num = int(input("Enter a number: "))


try:

    assert num % 2 == 0


except ZeroDivisionError:

    print(err)


except:

    print("Not an even number!")


else:

    reciprocal = 1/num

    print(reciprocal)

该代码无法正常工作并给出以下错误:


---------------------------------------------------------------------------

ZeroDivisionError                         Traceback (most recent call last)

<ipython-input-41-ce890375558f> in <module>

      8     print("Not an even number!")

      9 else:

---> 10     reciprocal = 1/num

     11     print(reciprocal)


ZeroDivisionError: division by zero


忽然笑
浏览 65回答 3
3回答

BIG阳

您认为为什么0 % 2应该提高ZeroDivisionError?简直就是0。检查数字是否为偶数时不需要例外,这绝对不是目的assert。相反,只需使用if:if num % 2 == 0:&nbsp; &nbsp; try:&nbsp; &nbsp; &nbsp; &nbsp; reciprocal = 1/num&nbsp; &nbsp; &nbsp; &nbsp; print(reciprocal)&nbsp; &nbsp; except ZeroDivisionError as err:&nbsp; &nbsp; &nbsp; &nbsp; print(err)else:&nbsp; &nbsp; print("Not an even number!")是否应该使用异常来处理这种情况num == 0是一个风格问题(我个人也只是if在这里使用一个声明)。在 Python 中,对这种情况使用异常处理比大多数其他语言更惯用。

ibeautiful

“reciprocal = 1/num”行必须位于 try 部分。像这样的东西:# program to print the reciprocal of even numbersnum = int(input("Enter a number: "))try:&nbsp; &nbsp; assert num % 2 == 0&nbsp; &nbsp; reciprocal = 1/num&nbsp; &nbsp; print(reciprocal)except ZeroDivisionError:&nbsp; &nbsp; print(err)except:&nbsp; &nbsp; print("Not an even number!")

暮色呼如

您没有用...包装正确的代码try/except...num % 2 == 0不会引发 a ZeroDivisionError(因为没有任何东西被零除...)并且无论如何它都在语句中assert...正如您从错误消息中看到的,错误来自reciprocal = 1/num这是在else部分中。您应该使用错误处理包装正确的代码,assert可以单独进行:num = int(input("Enter a number: "))assert num % 2 == 0, "Not an even number!"try:&nbsp; &nbsp; reciprocal = 1/num&nbsp; &nbsp; print(reciprocal)except ZeroDivisionError as err:&nbsp; &nbsp; print(err)除非您不希望引发(断言)错误,否则您可以执行以下操作:num = int(input("Enter a number: "))try:&nbsp; &nbsp; assert num % 2 == 0&nbsp; &nbsp; reciprocal = 1/num&nbsp; &nbsp; print(reciprocal)except ZeroDivisionError as err:&nbsp; &nbsp; print(err)except AssertionError:&nbsp; &nbsp; print("Not an even number!")
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python