您的位置:首页 > 其它

断言:assert

2015-07-02 10:17 239 查看
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

>>>


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: