python中斷言的用法

assert 語句,在需要確保程序中的某個條件一定爲真才能讓程序運行的話就非常有用
>>> age = 10
>>> assert 0 < age < 10
Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    assert 0 < age < 10
AssertionError
條件後可以添加字符串,用來解釋斷言
>>> age = -1
>>> assert 0 < age < 10, 'The age number must be realistic'
Traceback (most recent call last):
  File "<pyshell#5>", line 1, in <module>
    assert 0 < age < 10, 'The age number must be realistic'
AssertionError: The age number must be realistic

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章