Active February 13, 2022 / Viewed 161 / Comments 0 / Edit
Examples of how to assess if an expression is true in python using assert:
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')
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 !!
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 !
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!