python assert 断言基本用法

assert 关键字用于在代码中设置检查点,用于当程序出现错误时中断程序执行。

>>> a = 3
>>> assert 0 < a < 10
>>> a = 20
>>> assert 0 < a <10
Traceback (most recent call last):
  File "", line 1, in 
    assert 0 < a <10
AssertionError

# assert 条件后可以增加错误信息解释
>>> a = 20
>>> assert 0 < a < 10, '超出范围!'
Traceback (most recent call last):
  File "", line 1, in 
    assert 0 < a < 10, '超出范围!'
AssertionError: 超出范围!

你可能感兴趣的:(难点理解)