lettura simple

Assert in Python

In Python, the assert statement provides a quick and straightforward way to validate the truth of an expression. The syntax is pretty simple:

assert expression

If the expression evaluates to false, an AssertionError exception is immediately triggered.

Conversely, if the expression is true, the assert statement quietly proceeds with no impact.

The assert statement's flexibility even allows for a custom message to be displayed when an expression evaluates to false. Just add this message as a second parameter.

assert expression, message

Consider this real-world example.

We can use the assert statement to verify the truth of the following expression.

assert 2 + 2 == 4

No exceptions are thrown here because 2 + 2 equals 4 - that's true.

Now, let's evaluate a different expression.

assert 2 + 2 == 5

Python promptly raises an AssertionError, given that 2 + 2 equals 5 is, of course, false.

AssertionError

Customizing error messages is as simple as appending a string to the assert statement:

assert 2 + 2 == 5, "Incorrect mathematical operation"

In this case, Python will raise an AssertionError and display our custom error message because 2 + 2 equals 5 is false.

Incorrect mathematical operation

In conclusion, the assert statement is a powerful tool when you need to validate assumptions in your code, particularly useful during code debugging.

It’s a clean, professional way to ensure that your program is operating under the correct conditions.




Report a mistake or post a question




FacebookTwitterLinkedinLinkedin