The role of Python assert

Source: Internet
Author: User

One, the role of Python assert:

According to the official Python document (Https://docs.python.org/3/reference/simple_stmts.html#assert), "Assert statements is a convenient The-to-insert debugging assertions into a program.

Second, the general usage is:

Assert condition

Used to let the program test this condition, if condition is false, then raise a assertionerror out. Logically equivalent to:

If not condition:    raise Assertionerror ()

For example, the following examples:

>>> assert 1==1>>> assert 1==0traceback (most recent call last):  File "<pyshell#1>", line 1, I n <module>    assert 1==0assertionerror>>> assert true>>> assert Falsetraceback (most recent Call last):  File ' <pyshell#3> ', line 1, in <module>    assert falseassertionerror>>> assert 3 <2traceback (most recent):  File "<pyshell#4>", line 1, in <module>    assert 3< 2AssertionError

Iii. How to add an exception parameter for an ASSERT assertion statement

The exception argument to assert is to add string information after the assertion expression to explain the assertion and better know where the problem is. The format is as follows:

assert expression [, arguments]
assert expression [, parameter]

For example, the following examples:

>>> assert len (lists) >=5, ' list element number less than 5 '

Traceback (most recent):
File "d:/data/python/helloworld/helloworld.py", line 1, <module>
Assert 2>=5, ' list element number less than 5 '
Assertionerror: Number of list elements is less than 5

>>> assert 2==1, ' 2 not equal to 1 '

Traceback (most recent):
File "d:/data/python/helloworld/helloworld.py", line 1, <module>
Assert 2==1, ' 2 not equal to 1 '
Assertionerror:2 Not equal to 1

--------------------------------------------------------------------

Reference Links:

Https://www.cnblogs.com/liuchunxiao83/p/5298016.html

Https://www.cnblogs.com/cedrelaliu/p/5948567.html

The role of Python assert

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.