【发布时间】:2020-10-22 15:44:58
【问题描述】:
# 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
【问题讨论】:
-
你没有用
try/except包装正确的代码...num % 2 == 0不会引发ZeroDivisionError(因为没有任何东西被零除...)而且无论如何它都在一个assert声明...从错误消息中可以看出,错误来自reciprocal = 1/num,它位于else部分... -
另外 num % 2 不是检查 num == 0 -- 它是检查一个数字是否是偶数。
标签: python python-3.x