Python | assert关键字

Python断言assert是帮助代码流畅的调试工具。断言主要是假设程序员知道或总是希望是真的,因此将它们放在代码中,这样这些失败不会允许代码进一步执行。

简单地说,断言是一个布尔表达式,用来检查语句是True还是False。如果语句为True,则不执行任何操作并继续执行,但如果语句为False,则停止执行程序并抛出错误。

Python assert语句流程图

Python | assert关键字_第1张图片

Python assert关键字语法

语法: assert condition, error_message(optional)
参数
condition:返回True或False的布尔值条件。
error_message:在AssertionError的情况下,在控制台中打印的可选参数。
返回:AssertionError,如果条件计算为False。

在Python中,assert关键字有助于完成此任务。此语句接受一个布尔条件作为输入,当返回True时,不做任何事情并继续正常的执行流程,但如果计算结果为False,则引发AssertionError。

例如:

# 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)

输出

The value of a / b is : 
---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)
Input In [19], in <cell line: 10>()
      8 # using assert to check for 0
      9 print("The value of a / b is : ")
---> 10 assert b != 0
     11 print(a / b)

AssertionError: 

这段代码试图通过在执行除法操作之前检查b的值是否为0。a初始化为4,b初始化为0。程序打印消息a / b的值是:assert语句检查b是否不等于0。由于b为0,assert语句失败并引发AssertionError。
由于失败的assert语句引发异常,程序终止,不再继续执行下一行的print语句。

带有error_message参数的assert

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

在函数内部使用assert断言

在本例中,assert语句用于函数内部,以在计算矩形的面积之前验证矩形的长度和宽度是否为正。如果断言为False,则会引发AssertionError,并显示消息“Length and width must be positive”。如果断言为True,则函数返回矩形的面积;如果为False,则退出并返回一个错误。为了展示如何在各种情况下使用assert,该函数被调用两次,一次使用正输入,一次使用负输入。

def calculate_rectangle_area(length, width):
    # Assertion to check that the length and width are positive
    assert length > 0 and width > 0, "Length and width"+ \
                "must be positive"
    # Calculation of the area
    area = length * width
    # Return statement
    return area
 
 
# Calling the function with positive inputs
area1 = calculate_rectangle_area(5, 6)
print("Area of rectangle with length 5 and width 6 is", area1)
 
# Calling the function with negative inputs
area2 = calculate_rectangle_area(-5, 6)
print("Area of rectangle with length -5 and width 6 is", area2)

带有布尔值条件的断言

在这个例子中,assert语句检查布尔条件x < y是否为真。如果断言失败,则引发AssertionError。如果断言通过,程序将继续并打印x和y的值。

# Initializing variables
x = 10
y = 20
 
# Asserting a boolean condition
assert x < y
 
# Printing the values of x and y
print("x =", x)
print("y =", y)

输出

x = 10
y = 20

检查变量类型的断言

在本例中,assert语句检查变量a和b的类型是否分别为str和int。如果任何断言失败,它将引发AssertionError。如果两个断言都通过,程序继续并打印a和b的值。

# Initializing variables
a = "hello"
b = 42
 
# Asserting the type of a variable
assert type(a) == str
assert type(b) == int
 
# Printing the values of a and b
print("a =", a)
print("b =", b)

输出

a = hello
b = 42

断言字典的值

# Initializing a dictionary
my_dict = {"apple": 1, "banana": 2, "cherry": 3}

# Asserting the contents of the dictionary
assert my_dict["apple"] == 1
assert my_dict["banana"] == 2
assert my_dict["cherry"] == 3

# Printing the dictionary
print("My dictionary contains the following key-value pairs:", my_dict)

输出

My dictionary contains the following key-value pairs: 
{'apple': 1, 'banana': 2, 'cherry': 3}

实际应用

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

# 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

为什么要使用Python assert语句?

在Python中,assert语句是一个强大的调试工具,可以帮助识别错误并确保代码按预期运行。下面是使用assert的几个理由:

  • 调试:代码所做的假设可以用assert语句进行验证。通过在整个代码中放置assert语句,可以快速找到错误并调试程序。
  • 文档:在代码中使用assert语句可以作为文档。断言语句使其他人更容易理解和使用您的代码,因为它们显式地描述了您的代码所做的假设。
  • 测试:为了确保满足某些需求,在单元测试中经常使用assert语句。通过在测试中合并assert语句,可以确保代码正常工作,并且所做的任何更改都不会损坏当前功能。
  • 安全性:您可以使用assert检查程序输入是否符合要求并验证它们。通过这样做,可以避免诸如缓冲区溢出和SQL注入攻击的安全缺陷。

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