1. 程式人生 > >Assert-斷言

Assert-斷言

Assertions:斷言
斷言是一種健壯性檢查,當你用它已經完成程式的測試時,你可以繼續或停止。在斷言下,一個表示式將會被測試。如果結果是False,就會觸發異常。
1、用assert statement 來使用斷言語句,如:

print 1
assert 2+2==4
print 2
assert 1+1==3
print 3

執行結果:

1Traceback (most recent call last):
2

  File "D:\python2.7\s.py", line 6, in <module>
    assert 1+1==3
AssertionError

2、assert語句可以設定第二個引數,這個引數表明瞭如果錯誤發生時輸出的錯誤資訊,如:

temp=-10
assert(temp>=10),'Is negetive'

執行結果:

Traceback (most recent call last):
  File "D:\python2.7\s.py", line 4, in <module>
    assert(temp>=10),'Is negetive'
AssertionError: Is negetive