Assertions in Python are like quick “checkpoints”. The program either moves forward from there or terminates.

What is the assert statement in Python?

  • It’s a way of ensuring that a certain condition is met at any point in your code.
  • The assert statement uses a boolean expression, which raises an exception if the expression is evaluated as False.
  • The statements using assert are of the form:
1
assert <some condition>, <Error message if condition is false>
  • If the condition evaluates to True, i.e., we get “assert True” then the execution continues onto the next line.
  • If the condition evaluates to False, i.e., we get “assert False” then the program prints the error message (if specified) and terminates the program.
  • The error message part is optional, and if left unspecified, the program will simply halt and raise an Assertion Error.

Where are assertions used?

  • Assertions are generally used at the start of a function to check the validity of input, and after a function to check the validity of output.
  • They can also be used as a debugging tool to ensure that an erratic value is not carried forward through the entire program.
  • If an assertion fails and causes an error, the exact line at which the error occurred is known. Hence, the bugs are localized and easy to identify.

What are the benefits of using assert statements in Python code?

  • Simplified code – you don’t need to apply other conditional checks at different points in the program, because you already know that the condition has been verified, simply due to the lack of Assertion Error
  • Assertions can provide a way to verify any assumptions you may have stated in the comments of a code.
  • They run in constant time and hence do not significantly delay the execution time of the code, so there is little cost to using them.

Here’s an example to illustrate this:


1
2
3
4
5
6
7
Output:
Traceback (most recent call last):                                                                                    
  File "main.py", line 7, in &lt;module>                                                                                
    print(coffeeisbest(coffee,tea))                                                                                  
  File "main.py", line 4, in coffeeisbest                                                                            
    assert coffee>tea, "Something is wrong; it seems tea is greater than coffee!"                                    
AssertionError: Something is wrong; it seems tea is greater than coffee!

Leave a Reply

Your email address will not be published. Required fields are marked *