Tutorialsteacher

Follow Us

Python - Assert Statement

In Python, the assert statement is a powerful tool that helps with debugging and handling errors during development. It allows you to make assumptions about the code and catch potential issues early on.

The assert statements can be useful when testing functions or methods, as it allows you to ensure that the function is behaving as expected. Additionally, assert statements can be used to enforce certain conditions on the inputs or outputs of a function, such as ensuring that a parameter is within a certain range or that a return value meets certain criteria.

Syntax

assert condition [, Error Message] 

The assert statement works by evaluating a boolean condition and raising an AssertionError if the expression is false. If the specified condition evaluates to True then it continues to execute next statements, otherwise it raises the AssertionError exception with the specified error message.

The following example demonstrates a simple assert statement.

Example: assert
def division(x,y):
  assert y!=0, "y cannot be zero"
  
  print(x/y)
  
division(10,2) #5
division(10,0) #AssertionError: y cannot be zero

In the above example, the division() function contains the assert statement to check whether the y parameter is zero or not. If the assert condition y!=0 evalutes to be True, then it will continue to execute the next statement without any error. If it is true then it will raise an AssertionError with the error message y cannot be zero.

The AssertionError is a built-in exception that can be handled using the try-except block, as shown below:

Example: AssertionError
def division(x,y):
  assert y!=0, "y cannot be zero"
  
  print(x/y)
  
#call division() function in try block
try:
  division(10,0)
except AssertionError as msg:
  print(msg)
Output
y cannot be zero

Above, calling division(10,0) will raise an AssertionError, which will be handled by the except block. The error message in the assert statement will be passed as an argument to the exception argument msg, using as keyword.

In this way, the assert statements should be used in conjunction with other error handling techniques, such as try-except blocks and logging, to ensure that your code is robust and reliable.

Thus, the assert statement is a valuable tool for any Python developer looking to improve their debugging and error handling skills.