Assert Keyword in Python: The Tool for Analyzing and Testing

In the previous articles, the concept of exception handling and its approaches has been explained in detail:

In this article, you are going to the next step where you will be learning about the assert keyword that allows you to check whether a given condition is true in your code. So, without any further ado, let's get started.

Assert Keyword in Python:

The 'assert' keyword is a type of keyword argument in Python and is a debugging and testing tool that allows you to check whether a given condition is true. It helps you express your concerns about the state of the program and provides a way to catch potential errors early during development.

Syntax of Assert Keyword in Python:

The syntax of the 'assert' statement is as follows:

 >>> assert condition, message

Here,

  • 'condition': It is an expression that you expect to be true. It could be any valid Python expression that evaluates to either 'True' or 'False'. If the condition is 'True', the program continues its execution without any interruption. If the condition is 'False', an AssertionError exception is raised and the code will terminate.
  • 'message' (optional): It is an additional argument that allows you to provide a message associated with the assertion. This message is displayed as part of the error message when the 'AssertionError' occurs.

NOTE: When an 'AssertionError' is raised, it indicates that the assumption made by the 'assert' statement was not true, suggesting a potential bug or an unexpected state in the program.

Working of try...except…finally in Python:

  1. The program encounters an 'assert' statement with a specified condition to be checked.
  2. The condition is evaluated. If the condition is True, the program continues its execution without any interruption.
  3. If the condition is False, an 'AssertionError' exception is raised. This exception indicates that the assumption made by the 'assert' statement was not true.
  4. When the 'AssertionError' exception is raised, the program halts at the location of the 'assert' statement.
  5. The error message associated with the 'AssertionError' is displayed, including the location of the 'assert' statement that helps us to navigate to the error much faster.
  6. The error message helps by providing additional information about the cause of the assertion failure, aiding in debugging and identifying the issue.

Example Program for try…except…finally in Python:

Let's understand the concept much better with an example program.

 >>> def calculate_discount(price, discount) :
 >>>     assert discount >= 0 and discount <= 1, "Discount should be between 0 and 1."
 >>>     discounted_price = price - (price * discount)
 >>>     return discounted_price
 >>> # Example usage
 >>> print(calculate_discount(100, 0.2)) # Valid discount
 >>> print(calculate_discount(100, 1.5)) # Invalid discount
Output:

80

AssertionError: "Discount should be between 0 and 1."

In this example, the 'calculate_discount' function calculates the discounted price based on a given price and discount. The 'assert' statement is used to check if the discount provided is within the valid range of 0 to 1.

  • When the function is called with a valid discount, such as 'calculate_discount(100, 0.2)', the assertion condition '(discount >= 0 and discount <= 1)' evaluates to 'True'. The calculation proceeds, and the discounted price of 80 is printed.

  • When the function is called with an invalid discount, such as 'calculate_discount(100, 1.5)', the assertion condition evaluates to 'False' as the value is not between 0 and 1. This triggers an ;AssertionError; with the specified error message: "Discount should be between 0 and 1." The program halts, and the error message is displayed.

The 'assert statement' in this example ensures that the discount value provided falls within the expected range. If it doesn't, it raises an 'AssertionError', indicating that an invalid discount was provided. This helps catch potential errors and ensures that the discount calculation is performed correctly with valid inputs.

Conclusion:

In conclusion, by utilizing the assert keyword, you can validate assumptions about the state of your program, making it easier to identify and fix issues during development and testing.

I hope I explained this concept clearly enough for you to understand it completely. If you have any queries regarding this topic, feel free to contact us.


Learn via Video Course

Python Logo

Python

6109

7 hrs