How to assess if an expression is true in python using assert ?

Published: February 13, 2022

Updated: December 09, 2022

Tags: Python;

DMCA.com Protection Status

Examples of how to assess if an expression is true in python using assert:

Assert in python

Assert is usfeull to debug a code by inserting assertions into a program:

assert condition, 'error message'

It is equivalent to :

if not condition:
        raise AssertionError('error message')

Assert that a variable is a string

An example

s = 'Hello'

assert type(s) == str, 'Oups, it is not a string variable !!'

will returns nothing since s is a string here. However:

s = 1234

assert type(s) == str, 'Oups, it is not a string variable !!'

will stop python and returns

---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)
<ipython-input-30-3ccd9596b9bb> in <module>
            1 s = 1234
            2 
----> 3 assert type(s) == str, 'Oups, it is not a string variable !!'

AssertionError: Oups, it is not a string variable !!

Assert that a variable is equal to an expected value

Another example

cond = 2

assert cond == 2, 'Oups, something wrong here !'

returns nothing.

While

cond = 3

assert cond == 2, 'Oups, something wrong here !'

gives

---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)
<ipython-input-31-d4ef9eeb6598> in <module>
            1 cond = 3
            2 
----> 3 assert cond == 2, 'Oups, something wrong here !'

AssertionError: Oups, something wrong here !