個人博客,支持一下唄!https://raycoder.me
本文首發(fā)于Ray's Blog
什么是assert?它的中文名叫做斷言。我們先來看一個簡單的例子:
age = int(input())
if age>=18:
print('You can watch it!')
else:
print('You are too young!')
這個例子進行了一下18G操作,沒有達到18歲的人會被拒之門外友善的提示。
不過,我們可以通過assert關鍵字來實現(xiàn)同等的操作。
>>> age = int(input())
17
>>> assert age >= 18
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
assert age >= 18
AssertionError
age = int(input())
try:
assert age >= 18
print('You can watch it!')
except AssertionError:
print('You are too young!')
這只是一個簡單的例子,assert還可以進行更復雜的操作。
引用一段菜鳥教程。
assert的語法格式如下:
assert expression
等價于:
if not expression:
raise AssertionError
assert后面也可以緊跟參數(shù):
assert expression [, arguments]
等價于:
if not expression:
raise AssertionError(arguments)
如:
>>> assert True # 條件為 true 正常執(zhí)行
>>> assert False # 條件為 false 觸發(fā)異常
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AssertionError
>>> assert 1==1 # 條件為 true 正常執(zhí)行
>>> assert 1==2 # 條件為 false 觸發(fā)異常
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
>>>
以下實例判斷當前系統(tǒng)是否為 Linux,如果不滿足條件則直接觸發(fā)異常,不必執(zhí)行接下來的代碼:
import sys
assert ('linux' in sys.platform), "該代碼只能在 Linux 下執(zhí)行"
# 接下來要執(zhí)行的代碼
可以大大優(yōu)化我們的代碼,也可以減少if、elif、else的使用。
這個關鍵字也可以作校驗用,比如我們從網(wǎng)頁上下載了一個代碼,可以用assert來斷言本地代碼與網(wǎng)頁代碼相同,否則報錯。