assert(断言)用法

断言语句是将调试断言插入到程序中的一种方便方法。
1.用法

assert condition

让程序来测试condition,如果condition为false就会生成一个AssertionError。相当于:

if not condition:
    raise AssertionError()

2.示例

>>> assert 2 == 2
>>> assert 1 == 2
Traceback (most recent call last):
  File "", line 1, in 
    assert 1 == 2
AssertionError
>>> assert True
>>> assert False
Traceback (most recent call last):
  File "", line 1, in 
    assert False
AssertionError
>>> assert 1 > 2
Traceback (most recent call last):
  File "", line 1, in 
    assert 1 > 2
AssertionError
>>> 

3.添加异常参数(异常提示)
assert添加异常参数就是在异常表达式后面添加字符串信息,用来解释哪里出现了问题。表达式如下:
assert expression [, arguments]

示例:

>>> assert 1 == 2,'1不等于2'
Traceback (most recent call last):
  File "", line 1, in 
    assert 1 == 2,'1不等于2'
AssertionError: 1不等于2
>>> assert 1 > 2,'1小于2'
Traceback (most recent call last):
  File "", line 1, in 
    assert 1 > 2,'1小于2'
AssertionError: 1小于2
>>> 

你可能感兴趣的:(python,assert,Python)