Python3 assert
Python assert is used to judge an expression and triggers an exception when the expression condition is false.
An assertion can return an error directly when a condition is not met, without waiting for the program to crash after running; for example, if our code can only run on Linux, we can first check whether the current system meets the condition.

The syntax format is as follows:
assert expression
Equivalent to:
if not expression:
raise AssertionError
assert can also be followed immediately by an argument:
assert expression [, arguments]
Equivalent to:
if not expression:
raise AssertionError(arguments)
The following is an example of using assert:
assert
True
The condition is true, executes normally
assert
False
The condition is false, triggers an exception
Traceback
(
most recent call last
)
:
File
"
,
line
1
,
in
<
module
AssertionError
assert
1
==
1
The condition is true, executes normally
assert
1
==
2
The condition is false, triggers an exception
Traceback
(
most recent call last
)
:
File
"
,
line
1
,
in
<
module
AssertionError
assert
1
==
2
,
'1 is not equal to 2'
Traceback
(
most recent call last
)
:
File
"
,
line
1
,
in
<
module
AssertionError
:
1
Not equal
2
The following example checks whether the current system is Linux; if the condition is not met, an exception is triggered directly and the following code is not executed:
Example
import
sys
assert
(
'linux'
in
sys
.
platform
)
,
"This code can only be executed on Linux"
Python3 Errors and Exceptions