Python Assert

Python Assert

Python provides an assert statement which is used to check the logical expression. If the given logical expression is true, then it precedes for the next line; otherwise, it raises an Assertion Error.

It is also a debugging tool, which interrupts the program when an error occurred in the program and shows on which line the error has occurred. The syntax is given below:

Flow diagram

Python Assert

In the above flow diagram, Assertions are Boolean expressions that check if the given condition returns true or false. If it returns true, the program does nothing and moves to the next line of code. However, if it returns false, the program stops and shows an error.

Consider the below example, where we declare a function to divide two numbers.

Example-1 Using assert without error message

Output:

In the above program, when we call the function with passing argument 20 and 10, it gives 2.0 as a result. If we pass b as Zero, then it violates the condition and assert statement raise an Assertion error.

Example-2  Using assert with error message

Output:

We have passed numbers list and number1 as a non-empty list that’s why we got the output for the numbers and got AssertionError: List is empty for a non-empty list.

The assertion is used for:

  • Testing code.
  • Checking output of functions.
  • As a debugger to stop when an error occurs.
  • In checking values of arguments.

Key points to remember

  • assert statement accepts an expression and an optional message.
  • assert statement is used as a debugging tool.
  • assert statement is used to check types, values of the argument, and the output of the function.
  • Assertions are the condition or Boolean expression which is always supposed to be true in the code.