之前工作在測試中經常會碰到斷言掛起,每次出現斷言只知道有故障了,但是並沒有深究斷言是怎么回事,今天學習了python中的斷言語句,其實挺簡單。
1.assert語句的語法:
assert expression [,reason]
expression :表達式為真時,什么都不做,表達式為假時,拋出AssertionError異常;
reason:可選參數,用於對判斷條件進行描述,為了以后更好的知道哪里出現了問題。
2.assert語句只在調試階段有效。所以我們平時測試用的debug版本才會有斷言掛起,release版本沒有斷言。
apple=int(input("請輸入蘋果數量:")) children=int(input("請輸入小朋友的數量:")) assert apple>children,"蘋果不夠分" #結果 請輸入蘋果數量:10 請輸入小朋友的數量:20 Traceback (most recent call last): File "C:\Python27\main.py", line 9, in <module> assert apple>children,"蘋果不夠分" AssertionError: 蘋果不夠分 >>>