Home > Backend Development > Python Tutorial > What are python3 assertions

What are python3 assertions

(*-*)浩
Release: 2019-07-09 10:10:20
Original
3342 people have browsed it

As the name suggests, concludes that this is right. If it is wrong, there must be something wrong.

What are python3 assertions

Function prototype: assert expression (recommended learning: Python video tutorial)

As A special programming statement checks the correctness of an expression, which can be understood as "this must be true". If the expression is not true (False), an exception is thrown.

assert expression

等价于下面的个句式:
if __debug__:
    if not expression: raise AssertionError

assert也可以用于多个表达式的断言:
assert expression1, expression2
Copy after login

Usually there is no error in passing parameters, but writing a large number of parameter checks affects programming efficiency, and there is no need to check the legality of parameters. Avoid unintended consequences.

When the program runs to a certain node, it is determined that the value of a certain variable must be, or that the object must have a certain attribute, etc. To put it simply, it means to determine that something must be something, and if it is not, throw an exception.

Syntax:

assert expression [, arguments]
Copy after login

assert expression[, parameter]

If the statement you assert is correct, nothing will happen

But if there is an error, an ASSertionError exception will be thrown, and the error message can be customized

#出错时候
assert 1>5, "chucuo"
输出值为:
---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)
<ipython-input-5-6aa3d3e733df> in <module>()
----> 1 assert 2>5, "chucuo"

AssertionError: chucuo
Copy after login

If the assertion fails, the assert statement itself will throw an AssertionError:

You can use the -O parameter to turn off assert when starting the Python interpreter

For more Python-related technical articles, please visit the Python Tutorial column to learn!

The above is the detailed content of What are python3 assertions. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template