【Python】assert用法介紹

一、python assert的作用:

官方文檔: “Assert statements are a convenient way to insert debugging assertions into a program”.

二、一般的用法是:

assert condition

用來讓程序測試這個condition,如果condition爲false,那麼raise一個AssertionError出來。邏輯上等同於:

if not condition:
    raise AssertionError()

例子:

>>> assert 1 == 1
>>> assert 1 == 0
Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    assert 1==0
AssertionError

>>> assert True
>>> assert False
Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
    assert False
AssertionError

>>> assert 3<2
Traceback (most recent call last):
  File "<pyshell#4>", line 1, in <module>
    assert 3<2
AssertionError

三、如何爲assert斷言語句添加異常參數

assert的異常參數,其實就是在斷言表達式後添加字符串信息,用來解釋斷言並更好的知道是哪裏出了問題。格式如下:

assert expression [, arguments]
assert 表達式 [, 參數]

例子:

>>> assert len(lists) >=5,'列表元素個數小於5'
Traceback (most recent call last):
File "D:/Data/Python/helloworld/helloworld.py", line 1, in <module>
assert 2>=5,'列表元素個數小於5'
AssertionError: 列表元素個數小於5

>>> assert 2 == 1,'2不等於1'
Traceback (most recent call last):
File "D:/Data/Python/helloworld/helloworld.py", line 1, in <module>
assert 2 == 1,'2不等於1'
AssertionError: 2不等於1
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章