Python Lessons – 4.5 Asserts

Python lessons - 4.5 Asserts

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:

a = input("Insert a value: ")
a = int(a)
assert a <= 10
print("You inserted the value ",a)

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

>>>
Insert a value: 12
Traceback (most recent call last):
File "C:/Python34/prova.py", line 3, in <module>
assert a <= 10
AssertionError

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

a = input("Insert a value: ")
a = int(a)
assert (a <= 10),"The value has exceeded the threshold 10"
print("You inserted the value ",a)

Again, if you enter a value greater than 10

>>>
Insert a value: 12
Traceback (most recent call last):
File "C:/Python34/prova.py", line 3, in
assert (a <= 10),"The value has exceeded the threshold 10"
AssertionError: The value has exceeded the threshold 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.