- 【功能】:用於判斷一個表達式,在表達式條件爲 false 的時候觸發異常。
- 【用途】:斷言可以在條件不滿足程序運行的情況下直接返回錯誤,而不必等待程序運行後出現崩潰的情況,例如代碼只能在 Linux 系統下運行,可以先判斷當前系統是否符合條件。
- 【語法】:
assert expression(表達式)
等價於:
if not expression:
raise AssertionError(arguments)
- 【實例1】
>>> assert True # 條件爲 true 正常執行
>>> assert False # 條件爲 false 觸發異常
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AssertionError
>>> assert 1==1 # 條件爲 true 正常執行
>>> assert 1==2, '1 不等於 2'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AssertionError: 1 不等於 2
- 【實例2】
import sys
assert ('linux' in sys.platform), "該代碼只能在 Linux 下執行"
# 接下來要執行的代碼
參考:https://www.runoob.com/python3/python3-assert.html