Assert once with multiple conditions in Python
In this tutorial, we will learn how to assert once with multiple conditions in Python.
What is assert?
In python, assert
statement is used to check whether a condition is true or false.
- If the condition evaluates to true, assert works like
pass
keyword and doesn’t affect program execution. - If the condition evaluates to false, it affects the execution of the program and results in an
AssertionError
error.
Syntax
assert condition, message
where message
is an optional parameter.
Assert Once with Multiple Conditions:
You can combine multiple assert
statements into a single one using Boolean operators like and
, or
& not
. For example:
x = 24 y = 18 assert x > 0 and (y%2==0), "x must be positive and y must be even"
since both the conditions evaluates to true, it doesn’t affect the execution of the program but if any of the one conditions fails or evaluates to false. It will give the following output:
File "<string>", line 3, in <module> ERROR! AssertionError: x must be positive and y must be even
Conclusion:
The assert
statement is generally for debugging and testing code.
We’ve successfully learned to assert once with multiple conditions in Python., simplifying the solution for better understanding. I hope you found this tutorial informative!
Leave a Reply