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

Active February 13, 2022    /    Viewed 161    /    Comments 0    /    Edit


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 !

References


Card image cap
profile-image
Daidalos

Hi, I am Ben.

I have developed this web site from scratch with Django to share with everyone my notes. If you have any ideas or suggestions to improve the site, let me know ! (you can contact me using the form in the welcome page). Thanks!



Did you find this content useful ?, If so, please consider donating a tip to the author(s). MoonBooks.org is visited by millions of people each year and it will help us to maintain our servers and create new contents.

Amount