python assert断言的用法
生活随笔
收集整理的這篇文章主要介紹了
python assert断言的用法
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
使用assert斷言是學習python一個非常好的習慣,python assert 斷言句語格式及用法很簡單。在沒完善一個程序之前,我們不知道程序在哪里會出錯,與其讓它在運行最崩潰,不如在出現錯誤條件時就崩潰,這時候就需要assert斷言的幫助。
一般的用法是:
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參考:
https://www.cnblogs.com/cedrelaliu/p/5948567.html
https://www.cnblogs.com/liuchunxiao83/p/5298016.html
總結
以上是生活随笔為你收集整理的python assert断言的用法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Windows 下各种Python库的下
- 下一篇: python运行报错