Assert Keyword in Python

Assert Keyword in Python

6 mins read297 Views Comment
Updated on Aug 27, 2024 13:46 IST

Python Programming includes a keyword known as “assert” that functions by receiving a boolean condition as input. The “assert” statements in Python can help to improve the quality and reliability of code, making it easier to debug, test, and maintain over time.

2023_03_Feature-Image-Templates-8.jpg

In this article, we will discuss the assert keyword in Python and understand its use with the help of examples. We will be covering the following sections: 

Introduction to Assert Keyword in Python 

In Python, the assert keyword is a powerful tool for debugging and error handling. The keyword takes a boolean expression as input, and if the expression evaluates to True, the program continues executing. If the expression evaluates to False, the program halts and raises an AssertionError

For instance, when creating a function that involves division, it is crucial to ensure that the divisor is not zero. To prevent any potential errors or bugs in the code that may arise from this issue later on, an assert statement can be used to assert that the divisor should not be equal to zero. 

You can also explore: How to Use Return Keyword in Python

Python Assert Statement 

When using the assert statement in Python, it takes an expression to evaluate as input, along with an optional error message. Essentially, encountering an assert statement in the code can result in one of two outcomes:  

  • The code runs smoothly without any problems, or  
  • An AssertionError is raised, causing the program to terminate.  

To understand these situations better, it is necessary to comprehend why it is essential to use the assert statement. 

You can also explore: Super() Function in Python

Why Use Python Assert Statement? 

There are several reasons why using the assert statement in Python is beneficial: 

  • Debugging: The assert statement can be used to check if an assumption made in the code is valid or not. By checking these assumptions, it is possible to catch errors and bugs early on in the development process, making it easier to debug the code. 
  • Error handling: The assert statement can help to catch errors and prevent them from propagating further in the code. This can be particularly useful in large codebases where it can be challenging to track down the source of an error. 
  • Code documentation: Using assert statements can serve as a form of documentation for the code, indicating the assumptions and constraints that the code is designed to work within. 
  • Testing: Assert statements are often used in testing frameworks to check that the code behaves as expected. They can be used to verify that the output of a function is correct, or that a specific condition holds true. 

You can also explore, these articles:

Understanding Python startswith() Function
What is Python endsWith() Function?
Center() Function in Python

Syntax of Assert Keyword in Python

The syntax of “assert” keyword in Python is given as: 

assert expression 

Here, expression is the boolean condition that is to be evaluated. If the expression evaluates to True, then the program continues to execute. If it evaluates to False, then an AssertionError is raised. 

Additionally, you can include an optional error message that will be displayed if the assertion fails: 

assert expression, message 

In this case, message is a string that provides additional information about the error. If the assertion fails, this message will be displayed along with the AssertionError

Note that it is generally a good practice to use assert statements only for debugging and testing purposes, and not for error handling in production code. In production code, it is better to use Python try/except blocks [insert link] to handle errors in a more controlled manner. 

Recommended online courses

Best-suited Python courses for you

Learn Python with these high-rated online courses

– / –
40 hours
– / –
5 days
– / –
3 days
3 K
3 weeks
– / –
4 days
– / –
20 hours
– / –
2 months
Free
6 weeks

Examples of Using the Assert Keyword in Python 

Here are some examples of using the “assert” keyword in Python: 

Example 1: Basic Usage 


 
def divide(a, b):
assert b != 0, "Divisor cannot be zero"
return a / b
print(divide(10, 2)) # Output: 5.0
Copy code

Output: 

5.0 

Or, 


 
def divide(a, b):
assert b != 0, "Divisor cannot be zero"
return a / b
print(divide(10, 0))
Copy code

Output: 

#Raises AssertionError with the message “Divisor cannot be zero” 

You can also explore: Mastering String Manipulation with Python’s strip() Function

Example 2: Testing Function Output 


 
def sum(a, b):
return a + b
assert sum(2, 2) == 4
assert sum(0, 0) == 0
assert sum(-1, 1) == 0
Copy code

You can also explore: Python Yield(): A Comprehensive Guide to Understanding and Implementing the Keyword

Example 3: Verifying Input Parameters 


 
def area_of_rectangle(length, breadth):
assert length > 0 and breadth > 0, "Length and Breadth should be greater than zero"
return length * breadth
print(area_of_rectangle(5, 10))
Copy code

Output: 

50 

Or, 


 
def area_of_rectangle(length, breadth):
assert length > 0 and breadth > 0, "Length and Breadth should be greater than zero"
return length * breadth
print(area_of_rectangle(-5, 10))
Copy code

Output: 

#Raises AssertionError with the message “Length and Breadth should be greater than zero” 

You can also explore: Python Continue Statement: How to Skip Iterations and Streamline Code Execution

Example 4: Debugging 


 
def reverse_string(string):
assert type(string) == str, "Input should be a string"
return string[::-1]
print(reverse_string("Hello"))
Copy code

Output: 

olleH 

Or, 


 
def reverse_string(string):
assert type(string) == str, "Input should be a string"
return string[::-1]
print(reverse_string(123))
Copy code

Output: 

#Raises AssertionError with the message “Input should be a string” 

These are just a few examples of how the “assert” keyword can be used in Python to catch errors and bugs, test function outputs, verify input parameters, and debug code. 

What Does the Assertion Error do to our Code? 

When an assertion fails, Python raises an AssertionError exception. This stops the execution of the program and displays an error message on the console, indicating the location where the assertion failed and the optional message that was provided. 

If the assertion was in a function, the function call will terminate and the exception will propagate up the call stack until it is caught by a try/except block or until it reaches the top-level of the program, in which case the program will terminate. 

The AssertionError exception can be caught and handled using a try/except block, in which case you can customize the way that the error is handled or display a more user-friendly error message. 

It is important to note that the AssertionError exception should be used only for debugging and testing purposes, and not for error handling in production code. In production code, it is better to use try/except blocks to handle errors in a more controlled manner. 

You can also explore: Python Break Statement: How to Exit a Loop and Improve Code Efficiency

Endnotes 

Hope this article was helpful for you to understand how and why the assert statement is used in Python. If you wish to learn more about Python and practice Python programming, you can explore related articles here

FAQs

What is the main purpose of the assert statement?

The assert statement is mainly used for debugging and testing purposes. It helps to catch errors and bugs in the code by verifying logical assumptions and assumptions about function inputs and outputs.

When should you use assert statements in Python?

You should use assert statements in Python when you want to verify assumptions in your code, test function outputs, verify input parameters, or debug code.

What happens when an assert statement fails?

When an assert statement fails, Python raises an AssertionError exception, which stops the execution of the program and displays an error message indicating the location where the assertion failed and the optional message that was provided.

Can you disable assert statements in Python?

Yes, you can disable assert statements in Python by running the Python interpreter with the -O (optimize) option. This option causes all assert statements to be removed from the code, effectively disabling them.

Is it good practice to use assert statements for error handling in production code?

No, it is generally not good practice to use assert statements for error handling in production code. Assert statements should be used only for debugging and testing purposes. In production code, it is better to use try/except blocks to handle errors in a more controlled manner.

How can you handle AssertionError exceptions raised by assert statements?

You can handle AssertionError exceptions raised by assert statements using a try/except block. In the except block, you can customize the way that the error is handled or display a more user-friendly error message.

About the Author

This is a collection of insightful articles from domain experts in the fields of Cloud Computing, DevOps, AWS, Data Science, Machine Learning, AI, and Natural Language Processing. The range of topics caters to upski... Read Full Bio