簡體   English   中英

即使在使用 try 和 except 之后 ZeroDivisionError

[英]ZeroDivisionError even after using try and except

# 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

“reciprocal = 1/num”這一行必須在 try 部分。 像這樣的東西:

# program to print the reciprocal of even numbers

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

try:
    assert num % 2 == 0
    reciprocal = 1/num
    print(reciprocal)

except ZeroDivisionError:
    print(err)

except:
    print("Not an even number!")

為什么你認為0 % 2應該引發ZeroDivisionError 簡直就是0。

檢查數字是否為偶數時不需要異常,這絕對不是assert的目的。 相反,只需使用if

if num % 2 == 0:
    try:
        reciprocal = 1/num
        print(reciprocal)
    except ZeroDivisionError as err:
        print(err)
else:
    print("Not an even number!")

是否應該使用異常來處理num == 0是一個風格問題(我個人也會在這里使用if語句)。 在 Python 中,對這種情況使用異常處理比在大多數其他語言中更慣用。

你沒有用try/except包裝正確的代碼...... num % 2 == 0不會引發ZeroDivisionError (因為沒有任何東西被零除......),無論如何它在assert語句中......正如你從錯誤信息可以看出,錯誤來自於else部分的reciprocal = 1/num

您應該使用錯誤處理包裝正確的代碼, assert可以單獨進行:

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

assert num % 2 == 0, "Not an even number!"
try:
    reciprocal = 1/num
    print(reciprocal)
except ZeroDivisionError as err:
    print(err)

除非您不希望引發(斷言)錯誤,否則您可以執行以下操作:

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

try:
    assert num % 2 == 0
    reciprocal = 1/num
    print(reciprocal)

except ZeroDivisionError as err:
    print(err)

except AssertionError:
    print("Not an even number!")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM