Use of assert statement in Python

  1. Assert statement are used to check whether the given logical or condition is True or False.
  2. if the condition is True, the program will continue to execute next line of code..
  3. However, if the condition is False then the program will stop the execution and raise an AssertionError.
  4. Assert statement is defined using assert keyword in Python. Assertions are always supposed to be True.

Syntax:

Assert condition [Error Message]

Example 1:

assert statement without error message

Example 2:

assert statement with error message

Example 3:

assert statement with try & except

Example 4:

assert statement with function

Above, square(10) will return 100, whereas square(-10) will raise an AssertionError because we passed -10.

Popular Posts

Spread the knowledge
 
  

Leave a Reply

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