python assert
时间: 2023-10-14 21:21:45 浏览: 91
python中assert用法实例分析
The assert statement in Python is used to check whether a specified condition is true or false. If the condition is true, the program will continue to run as normal. If the condition is false, an AssertionError will be raised and the program will stop running.
The syntax for the assert statement is:
```
assert condition, message
```
Where condition is the expression to be checked and message is an optional string that will be displayed if the assertion fails.
For example, the following code uses assert to check if a list contains a specific element:
```
my_list = [1, 2, 3, 4, 5]
assert 6 in my_list, "6 is not in the list"
```
In this case, the assertion fails because 6 is not in the list, so an AssertionError is raised and the message "6 is not in the list" is displayed.
阅读全文