Python assert 關鍵字


每種程式語言都有處理程式執行過程中引發的異常的功能。在 Python 中,assert 關鍵字用於捕獲錯誤並提示使用者自定義錯誤訊息,而不是系統生成的錯誤訊息。當發生錯誤時,這可以幫助程式設計師輕鬆找到並修復錯誤。

帶有 Assert

在以下示例中,我們使用 assert 關鍵字來捕獲除以零錯誤。訊息根據程式設計師的意願編寫。

示例

 現場演示

x = 4
y = 0
assert y != 0, "if you divide by 0 it gives error"
print("Given values are ","x:",x ,"y:",y)
print("\nmultiplication of x and y is",x * y)
print("\ndivision of x and y is",x / y)

執行以上程式碼,得到以下結果

Traceback (most recent call last):
File "scratch.py", line 3, in
assert y != 0, "if you divide by 0 it gives error"
AssertionError: if you divide by 0 it gives error

不帶 Assert

如果沒有 assert 語句,我們將得到系統生成的錯誤,這些錯誤可能需要進一步調查,以瞭解並找到錯誤源。

示例

 現場演示

x = 4
y = 0
#assert y != 0, "if you divide by 0 it gives error"
print("Given values are ","x:",x ,"y:",y)
print("\nmultiplication of x and y is",x * y)
print("\ndivision of x and y is",x / y)

執行以上程式碼,得到以下結果

multiplication of x and y is 0
Traceback (most recent call last):
File "scratch.py", line 6, in <module>
print("\ndivision of x and y is",x / y)
ZeroDivisionError: division by zero

更新於: 2020 年 1 月 2 日

229 次瀏覽

開始你的 職業生涯

透過完成課程來獲得證書

開始
廣告
© . All rights reserved.