Python3 assert(斷言)


Python assert(斷言)用於判斷一個表達式,在表達式條件為 false 的時候觸發異常。

語法格式如下:

assert expression

 等價於:

if not expression:
    raise AssertionError

 assert 后面也可以緊跟參數:

assert expression [, arguments]

 等價於:

if not expression:
    raise AssertionError(arguments)

以下為 assert 使用實例:

>>> 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    # 條件為 false 觸發異常
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AssertionError 
>>> assert 1==2, '1 不等於 2'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AssertionError: 1 不等於 2

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM