if not condition:
crash program
与其让程序晚点崩溃,不然在错误的条件出现时直接崩溃。哈哈。以为然。
在检查函数参数的属性时,或者作为初期测试和调试过程中的辅助条件。语句中使用关键字:assert
>>> age = 16
>>> assert 0 < age < 120
>>> age = -1
>>> assert 0 < age <120
Traceback (most recent call last):
File "<pyshell#10>", line 1, in <module>
assert 0 < age <120
AssertionError
>>>
如果需要确保程序中的某个条件一定为真才能让程序正常工作的话,assert语句就有用公里。它可以在在程序中置入检查点。
条件后可以添加字符串,用来解释断言。
>>> age = -1
>>> assert 0 <age < 120 ,'The age must be realistic'
Traceback (most recent call last):
File "<pyshell#31>", line 1, in <module>
assert 0 <age < 120 ,'The age must be realistic'
AssertionError: The age must be realistic
>>>