Python assert keyword
Assertions in any programming language are the debugging tools that help in the smooth flow of code. Assertions are mainly assumptions that a programmer knows always wants to be true and hence puts them in code so that failure of them doesn’t allow the code to execute further.
In simpler terms, we can say that assertion is the boolean expression that checks if the statement is True or False. If the statement is true then it does nothing and continues the execution but if the statement is False then it stops the execution of the program and throws an error. Let us look at the flowchart of the assertion.
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course
Flowchart of Assertion
Assert Keyword in Python
In python assert keyword helps in achieving this task. This statement simply takes input a boolean condition, which when returns true doesn’t return anything, but if it is computed to be false, then it raises an AssertionError along with the optional message provided.
Syntax : assert condition, error_message(optional)
condition : The boolean condition returning true or false.
error_message : The optional argument to be printed in console in case of AssertionError
Returns AssertionError, in case the condition evaluates to false along with the error message which when provided.
Example 1: Python assert keyword without error message
Example 2: Python assert keyword with error message
AssertionError: Zero Division Error
This has a much greater utility in testing and Quality assurance role in any development domain. Different types of assertions are used depending upon the application. Below is the simpler demonstration of a program that only allows only the batch with all hot food to be dispatched, else rejects the whole batch.
40 is O.K 26 is O.K 39 is O.K 30 is O.K
Runtime Exception :
AssertionError: Batch is Rejected