Python Assert Statement – How To Use Assert In Python

By Sruthy

By Sruthy

Sruthy, with her 10+ years of experience, is a dynamic professional who seamlessly blends her creative soul with technical prowess. With a Technical Degree in Graphics Design and Communications and a Bachelor’s Degree in Electronics and Communication, she brings a unique combination of artistic flair…

Learn about our editorial policies.
Updated January 15, 2025

Learn all about Python Assert Statement in this tutorial:

An assertion is a declaration that asserts or conditions confidently in the program.

For example, when the user is writing the division function in the Python program, he/she is confident that the divisor cannot be zero. The user will assert the divisor which is not equal to zero.

In Python, the Assertion is a boolean expression that checks whether the condition returns true or false. If the condition is true then, the further program will be executed i.e. the Assertion will not affect the program and it moves to the next line of code of the program.

=> Read Through The Entire Python Training Series Here

But, if the condition is false, then it will throw the Assertion Error and stop the execution of the program.

It acts as a debugging tool because it will halt the program when the error occurs and show it on the screen. The below flowchart will help to understand the working of the Assertion in Python.

Python assert

Python Assert: An In-Depth Look

Assertion in Python

If the program is bug-free then, these types of conditions will never occur in the future. Otherwise, if they occur then, the program will clash with the errors. This tool makes it easy for the developers to track the errors and fix them.

Python Assert Statement

Python supports built-in assert statements. The user can use the assertion conditions in the Python program. Assert statements have further conditions or we can say expressions that are supposed to be true always. If the assert condition is false, then it will halt the program and throw the Assertion Error.

Basic Syntax of Assertion in Python

```
assert <condition>
assert <condition>, <error message>
```

Python Assertion can be used in two ways:

  • If the “ assert “ condition is false or does not satisfy the condition then, it will halt the program and show the Assertion Error.
  • Assert statements can have further conditions for elective error messages. If the condition is false then, the execution of the program will stop and it will throw the Assertion Error with the error message.

How to Use Assert in Python

Let us take an example and understand the Assertions in a better way. In the following example, the user creates a function that will calculate the sum of the numbers with a condition that the values cannot be an empty list.

The user will use the “ assert “ statement to check whether the length of the passed list is zero or not and halts the program.

Example 1: Python assert using without Error Message

```
def Calculate_sum(numbers):
    assert len(numbers) != 0 # Condition: List can not be empty
    return sum(numbers)/len(numbers)

num = []
print( " Calculated sum of given numbers: ", Calculate_sum(num))
```

When the above program will be executed, it will throw the below error in the output.

Without Error Message

The user will get an error because he/she passed the empty list as an input to the assert statement. Due to this the Assertion condition will become false and stop the execution of the program.

So, in the next example, let us pass the non-empty list and see what will happen!

Example 2: Python assert using with an error message

```
def Calculate_sum(numbers):
    assert len(numbers) != 0 # Condition: List can not be empty
    return sum(numbers)/len(numbers)

num_1 = [1,2,3,4,5,6,7,8,9]
print( " Calculated sum of given numbers: ", Calculate_sum(num_1))

num_2 = []
print( " Calculated sum of given numbers: ", Calculate_sum(num_2))
```

Output:

Python assert using with error message

In the output, you will clearly see that we pass the non-empty list to the “ demo_mark_2 ” and get the calculated average as an output which means “ demo_mark_2 ” satisfies the assert condition.

But, again we pass the empty list to the “ demo_mark_1 ” and get the same error as shown above.

Example 3

```
def Calculate_sum(numbers):
    assert len(numbers) != 0 # Condition: List can not be empty
    return sum(numbers)/len(numbers)

num_1 = [1,2,3,4,5,6,7,8,9]
print( " Calculated sum of given numbers: ", Calculate_sum(num_1))

num_2 = [8,5,6,7,4,3]
print( " Calculated sum of given numbers: ", Calculate_sum(num_2))
```

Output

Python Assert Example

Frequently Asked Questions

Q #1) What does assert do in Python?

Answer: While performing the Assertions in Python, the “ assert ” keywords are used to debug the code. It will check whether the condition is true or false. If false, it will throw an error otherwise will continue to execute the program code.

Q #2) Can we catch the assertion error?

Answer: In Python, to catch the assertion error, the user will need to define the declaration of the assertion statement in the try block of code and then, catch the assertion error in the catch block of the code.

Q #3) How do you assert true in Python?

Answer: In Python to use the assert true, “assertTrue()” is used which is an unittest library function that is used to perform the unit testing to compare and check the test value with true.

The “ assertTrue() ” will take the two parameters as an input from the user and return the boolean value which depends upon the assert condition. If the test value is true then, the “ assertTrue() ” function will return True otherwise it will return False.

Q #4) Should you use assert in Python?

Answer: Yes we can use assert in Python. Python supports built-in assert statements. The user can use the assertion conditions in the program. Assert statements are the conditions that are supposed to be true always. If the assert condition is false, it will stop the Python program and throw the Assertion error.

Conclusion

In the above tutorial, we learned the concept of the Assertion statement in Python.

  • Introduction of Assertion in Python
  • Assertion Statement in Python
  • Basic Syntax of Assertion in Python

Given below are some key points to remember while using the “ assert ” in the Python program to perform the Assertions.

  • An assertion is a condition or we say a boolean expression that is supposed to be true always.
  • In Python, assert statements will take an expression along with an elective message.
  • It will act as a debugging tool and halt the Python program when the error occurs.

=> Check ALL Python Tutorial Here

Was this helpful?

Thanks for your feedback!

Leave a Comment