Python Assert Keyword
The assert keyword is a tool used for debugging the Python code. It tests whether the condition you are testing in your code is True or False.
If the condition is True, then nothing happens, but if it’s False, Python raises an AssertionError.
Syntax of the assert keyword: assert test_condition [, message]
Let’s have an example
In the above example, while executing the first statement variable x was equal to 3, therefore the code executed. But when the condition returned False, we got the AssertionError.
Let’s have another example to get a better insight on what other things you can do with the assert keyword.
It must be clear from the above two examples that you can use any type of condition that gives boolean results.
The important part of the assert keyword is that you can pass a message along with the condition. It is very helpful while debugging. The message passed alongside will show when the assert condition becomes False.
The AssertionError is raised in the above example. This triggers the message written with the assert code. Also, as the AssertionError interrupts the code execution, our print statement will not get executed.
A more practical use of the assert keyword is in quality testing, or any type of testing whatsoever. For example: –
A more practical use of the assert keyword is in testing scenario, especially while performing Quality testing. Let’s check the example below.
You can try other examples on your own too to get more ideas on where to use assert keyword.