断言(assert)的语法类似 if 条件分支语句的“近亲”;
当assert关键字后面的条件为假时,程序自动崩溃,并抛出AsswerionError异常;
assert常用于程序测试中,在程序中置于检查点,当需要确保程序中某个条件一定为真才能让程序工作时,可以在错误的条件出现时,让程序“自我毁灭”。
a = 1
b = 1
#条件不满足,报错AssertionError
assert a > b
Traceback (most recent call last):
File "<input>", line 1, in <module>
AssertionError
assert a < b
Traceback (most recent call last):
File "<input>", line 1, in <module>
AssertionError
#条件满足,正常执行
assert a == b
程序示例:
a = int(input('输入a:'))
b = int(input('输入b:'))
print(f'断言前,a = {a},b = {b}')
assert a == b
print(f'断言后,a = {a},b = {b}')
程序执行:
#断言条件通过&#