8.4 making assertions

8.4 making assertions

>> assert 1+1==2
>>> assert 1+1==3
Traceback (most recent call last):
File “”, line 1, in
AssertionError
>>> assert 2+2==5, “only for very large values of 2”
Traceback (most recent call last):
File “”, line 1, in
AssertionError: only for very large values of 2
>>>
(1)assert声明后面跟随一个有效的表达式,并且表达式的结果为True,那么assert什么都不做!如果结果为False的话会引发AssertionError错误。
(2)在引发AssertionError时可以包含一条可读的信息。
assert len(unique_characters) <= 10, 'Too many letters'

等于

if len(unique_characters) > 10:
     raise AssertionError('Too many letters')

发表评论