📜  Python断言关键字

📅  最后修改于: 2022-05-13 01:55:51.428000             🧑  作者: Mango

Python断言关键字

任何编程语言中的断言都是有助于代码顺畅流动的调试工具。断言主要是程序员知道或总是希望为真并因此将它们放入代码中的假设,因此这些假设的失败不允许代码进一步执行。

简单来说,我们可以说断言是检查语句是真还是假的布尔表达式。如果该语句为真,则它什么也不做并继续执行,但如果该语句为假,则它停止程序的执行并引发错误。

让我们看一下断言的流程图。

断言流程图

Python 断言关键字

在Python中断言关键字

在Python中, assert关键字有助于完成这项任务。此语句将布尔条件作为输入,当返回 true 时不执行任何操作并继续正常的执行流程,但如果计算结果为 false,则会引发 AssertionError 以及提供的可选消息。

示例 1:没有错误消息的Python assert 关键字

Python3
# Python 3 code to demonstrate
# working of assert
 
# initializing number
a = 4
b = 0
 
# using assert to check for 0
print("The value of a / b is : ")
assert b != 0
print(a / b)


Python3
# Python 3 code to demonstrate
# working of assert
 
# initializing number
a = 4
b = 0
 
# using assert to check for 0
print("The value of a / b is : ")
assert b != 0, "Zero Division Error"
print(a / b)


Python3
# Python 3 code to demonstrate
# working of assert
# Application
 
# initializing list of foods temperatures
batch = [ 40, 26, 39, 30, 25, 21]
 
# initializing cut temperature
cut = 26
 
# using assert to check for temperature greater than cut
for i in batch:
    assert i >= 26, "Batch is Rejected"
    print (str(i) + " is O.K" )


输出 :

AssertionError: 

示例 2:带有错误消息的Python断言关键字

Python3

# Python 3 code to demonstrate
# working of assert
 
# initializing number
a = 4
b = 0
 
# using assert to check for 0
print("The value of a / b is : ")
assert b != 0, "Zero Division Error"
print(a / b)

输出:

AssertionError: Zero Division Error

实际应用

这在任何开发领域的测试和质量保证角色中都具有更大的实用性。根据应用程序使用不同类型的断言。下面是一个程序的简单演示,该程序只允许发送带有所有热食的批次,否则拒绝整个批次。

Python3

# Python 3 code to demonstrate
# working of assert
# Application
 
# initializing list of foods temperatures
batch = [ 40, 26, 39, 30, 25, 21]
 
# initializing cut temperature
cut = 26
 
# using assert to check for temperature greater than cut
for i in batch:
    assert i >= 26, "Batch is Rejected"
    print (str(i) + " is O.K" )

输出 :

40 is O.K
26 is O.K
39 is O.K
30 is O.K

运行时异常:

AssertionError: Batch is Rejected