Python 简明教程
Python - Assertions
Assertions in Python
Python 中的断言是断言或假定条件为真的语句。如果条件变为 false,Python 会引发 AssertionError 异常。它们用于检测如果没有正确的代码就永远不会发生的编程错误。
Assertions in Python are statements that assert or assume a condition to be true. If the condition turns out to be false, Python raises an AssertionError exception. They are used to detect programming errors that should never occur if the code is correct.
-
The easiest way to think of an assertion is to liken it to a raise-if statement (or to be more accurate, a raise-if-not statement). An expression is tested, and if the result comes up false, an exception is raised.
-
Assertions are carried out by the assert statement, the newest keyword to Python, introduced in version 1.5.
-
Programmers often place assertions at the start of a function to check for valid input, and after a function call to check for valid output.
The assert Statement
在 Python 中,断言使用 assert 关键字,后跟一个表达式。如果表达式计算结果为 False,会引发 AssertionError。以下是断言的语法 −
In Python, assertions use the assert keyword followed by an expression. If the expression evaluates to False, an AssertionError is raised. Following is the syntax of assertion −
assert condition, message
其中,
Where,
-
condition − A boolean expression that should be true.
-
message (optional) − An optional message to be displayed if the assertion fails.
Using Assertions
断言通常在开发和测试阶段使用,以检查始终保持为真的条件。
Assertions are generally used during development and testing phases to check conditions that should always hold true.
Example
在以下示例中,我们使用断言来确保变量“num”介于“0”到“100”的有效范围内。如果断言失败,Python 会引发“AssertionError”,阻止后续 print 语句的进一步执行 −
In the following example, we are using assertions to ensure that the variable "num" falls within the valid range of "0" to "100". If the assertion fails, Python raises an "AssertionError", preventing further execution of the subsequent print statement −
print('Enter marks out of 100:')
num = 75
assert num >= 0 and num <= 100
print('Marks obtained:', num)
num = 125
assert num >= 0 and num <= 100
print('Marks obtained:', num) # This line won't be reached if assertion fails
以下是上面代码的输出: -
Following is the output of the above code −
Enter marks out of 100:
Marks obtained: 75
Traceback (most recent call last):
File "/home/cg/root/66723bd115007/main.py", line 7, in <module>
assert num >= 0 and num <= 100
AssertionError
Custom Error Messages
要在断言失败时显示自定义错误消息,请在 assert 语句的表达式后包含一个字符串 −
To display a custom error message when an assertion fails, include a string after the expression in the assert statement −
assert num >= 0 and num <= 100, "Only numbers in the range 0-100 are accepted"
Handling AssertionError
可以使用 try-except 块像处理任何其他异常一样捕获并处理断言。如果它们未得到处理,它们将终止程序并生成回溯 −
Assertions can be caught and handled like any other exception using a try-except block. If they are not handled, they will terminate the program and produce a traceback −
try:
num = int(input('Enter a number: '))
assert num >= 0, "Only non-negative numbers are accepted"
print(num)
except AssertionError as msg:
print(msg)
它将生成如下输出:
It will produce the following output −
Enter a number: -87
Only non-negative numbers are accepted
Assertions vs. Exceptions
断言用于检查始终为真的内部状态和不变量。而异常有助于处理在正常执行期间可能出现的运行时错误和异常情况。
Assertions are used to check internal state and invariants that should always be true. Whereas, exceptions helps in handling runtime errors and exceptional conditions that may occur during normal execution.
Python 优化模式(-O 或 python -O script.py )中默认禁用断言。因此,它们不应用于实施生产环境中程序正确运行所需的约束。
Assertions are disabled by default in Python’s optimized mode (-O or python -O script.py). Therefore, they should not be used to enforce constraints that are required for the correct functioning of the program in production environments.