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:
assertor assert
Flow diagram

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
def fun(a,b): assert b!=0 c= a/b return c print(fun(20,10)) print(fun(20,0))
Output:
line 2, in fun 2.0 assert b!=0 AssertionError
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
def avg(numbers): assert len(numbers)!=0 sum = 0 for temp in numbers: sum = temp+sum return sum/len(numbers) numbers = [53,56,85,90,45,95] print("The average is:",avg(numbers)) numbers1 =[] # An Empty list print("The average is:",avg(numbers1))
Output:
The average is: 70.67 line 2, in avg assert len(numbers)!=0,"List is empty" AssertionError: List is empty
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.