See how you stack up against top hiring criteria for the role in 2025.
Compare against 1000+ live job postings
Identify critical technical skill gaps
Get a personalized improvement roadmap
No signup required, takes less than 30 sec
Introduction
For a long time, Python has been a very well-liked programming language. This is primarily because of its adaptability and simple syntax. One of the most amazing programming concepts of python is an Assertion that helps us to test an expression.
In Python, an AssertionError is an exception that occurs when an assert statement fails.
This article will guide you through the Assertionerror Python followed by its working and the steps required to avoid the error.
Before we start with the AssertionError, let us first understand what an Assert statement is.
A brief about Assert Statement
In Python, assert is a built-in keyword used for debugging and testing purposes. It allows you to check whether a given condition is true during the execution of your program.
Here is the syntax of the Assert Statement:
python
python
assert condition, message
You can also try this code with Online Python Compiler
condition: The expression that you want to check. It should evaluate to either True or False
message: (Optional) An additional message that you can provide to explain why the condition should be true. This message will be displayed if the condition is false
AssertionError Python
If the condition is false, it raises an AssertionError exception, stopping the program's execution and indicating that something unexpected has happened.
Let us try out some examples to see the occurrence of the exception AssertionError:
In this example, we will divide two numbers.
python
python
def divide(a, b):
assert b != 0, "Cannot divide by zero!"
return a / b
result = divide(10, 2)
print(result)
You can also try this code with Online Python Compiler
Next let us see the ways to avoid the AssertionError python:
Ways to avoid AssertionError Python
There are multiple ways to avoid the AssertionError python, which you can choose based on your requirements.
1. Using -O flag
The -O flag can be used to disable all assert statements in the program. By disabling the assert statements in the program, you can avoid the AssertionError exception in Python.
When you run a Python script with this flag, all the assert statements in the code will be ignored, and they will not raise AssertionError exceptions.
Note: This is useful when you want to run the code in a production environment and eliminate any overhead caused by assertions, as they are mainly intended for debugging and testing during development.
Example: $ python -O example.py
You can also try this code with Online Python Compiler
You may use try-except statements to handle the AssertionError in python. Let us see an example to illustrate the statement.
python
python
def check_numbers(numbers):
assert isinstance(numbers, list), "Input must be a list."
assert all(isinstance(num, int) for num in numbers), "All elements must be integers."
assert len(numbers) >= 5, "The list must contain at least five elements."
assert sum(numbers) > 0, "Sum of elements should be greater than zero."
try:
numbers1 = [10, 20, 30, 40, 50]
check_numbers(numbers1)
numbers2 = [1, 2, '3', 4, 5] # '3' is not an integer
check_numbers(numbers2)
numbers3 = [1, 2, 3, 4] # Less than five elements
check_numbers(numbers3)
numbers4 = [-1, -2, -3, -4, -5] # Sum is not greater than zero
check_numbers(numbers4)
except AssertionError as e:
print(f"AssertionError: {e}")
You can also try this code with Online Python Compiler
Important: You must be wondering why only one statement got caught? What about the other input values?
The reason the other exceptions are not being shown in the output is that the check_numbers function raises AssertionError when any of the assert statements fail. Since the function is called within the try block, it stops execution immediately after the first AssertionError occurs and does not proceed to the other test cases.
If we want other exceptions to be thrown as well, we need to provide the except statement after every input test case.
python
python
def check_numbers(numbers):
assert isinstance(numbers, list), "Input must be a list."
assert all(isinstance(num, int) for num in numbers), "All elements must be integers."
assert len(numbers) >= 5, "The list must contain at least five elements."
assert sum(numbers) > 0, "Sum of elements should be greater than zero."
try:
numbers1 = [10, 20, 30, 40, 50]
check_numbers(numbers1)
except AssertionError as e:
print(f"Test Case 1: AssertionError - {e}")
try:
numbers2 = [1, 2, '3', 4, 5] # '3' is not an integer
check_numbers(numbers2)
except AssertionError as e:
print(f"Test Case 2: AssertionError - {e}")
try:
numbers3 = [1, 2, 3, 4] # Less than five elements
check_numbers(numbers3)
except AssertionError as e:
print(f"Test Case 3: AssertionError - {e}")
try:
numbers4 = [-1, -2, -3, -4, -5] # Sum is not greater than zero
check_numbers(numbers4)
except AssertionError as e:
print(f"Test Case 4: AssertionError - {e}")
You can also try this code with Online Python Compiler
You can use unit testing frameworks like unittest or pytest to write test cases that assert the expected behavior when assert statements pass or fail. These test cases can help ensure the correctness of your code during development.
What is the main advantage of using assert statements in Python?
The primary advantage of assert statements is that they provide a simple and convenient way to perform sanity checks and validate assumptions during development and testing. They help detect logical errors early in the code, making debugging more efficient.
What makes Python so popular?
Python is one of the most loved user-friendly programming languages available because of its simple syntax and emphasis on natural language.
What is the difference between assert and regular exception handling?
assert is primarily used for debugging and testing, whereas regular exception handling (try, except, raise) is used for more robust error handling in production code. assert is usually removed from optimized production code, while regular exception handling remains active.
Conclusion
To wrap up the article, we have extensively discussed the AssertionError in python.
We have also discussed the ways to avoid the AssertionError Python and handling it using try and except block.
Refer to our Guided PathonCodeStudioto upskill yourself in Python programming language, Competitive Programming, JavaScript, System Design, and many more! If you want to test your competency in coding, check out the mocktest series and participate in the contests hosted on CodeStudio! But you have just started your learning process and are looking for questions from tech giants like Amazon, Microsoft, Uber, etc. In that case, you must look at the problems,interview experiences, and interview bundle for placement preparations.
Nevertheless, consider our paid courses to give your career an edge over others!
Do upvote our blogs if you find them helpful and engaging!