Python Lessons – 4.5 Asserts

Python lessons - 4.5 Asserts


The asserts are a very useful control tool to be used during the drafting of a code under test (DEBUG).

Each assertion introduced in the code performs a check at a precise moment of execution, using a condition. If the condition is met then execution continues, otherwise an AssertError exception is blocked that blocks program execution.

These assertions can be activated and deactivated. You will activate them when you want to carry out checks, you will deactivate them when you are sure of the execution.

Thus the assertions can be used as checkpoints, useful to take into account the progress of the program, for example by verifying the content or value of some variables.

Very often assertions are added at the beginning of the definition of a function, to carry out checks on the validity of incoming arguments, and also at the output of a function, when it is necessary to check the validity of the return value of the function.

To define an assertion, the assert clause is used.

assert condition

For example:

By entering a value greater than 10, the assertion fails and the exception is thrown, blocking program execution.

Additionally, assert can accept a second argument, which is the error message that follows the exception

Again, if you enter a value greater than 10

⇐ Go to Python Lesson 4.4 – Raise

Go to Python Lesson 4.6  – Opening files ⇒

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.