根據Python 官方文檔解釋(https://docs.python.org/3/reference/simple_stmts.html#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