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