Hurry! Try our new Interactive Courses for FREE. 🥳   🚀
  Signup/Sign In

What is the use of assert in Python?

In this article, we will learn about an assert keyword and its use in Python. We will discuss the usage with examples. Let's first have a quick look over what is an assert in Python.

What is assert in Python?

assert is a keyword in Python. It acts more like a statement than a function. It is basically a conditional check debugging tool for handling errors. It somewhat works like if-else a statement but acts like catching exceptions. It halts the program run when the assert statement encounters an error. It also tells where the error has occurred.

The assert statement involves a condition or expression which is supposed to be always true. If the condition is false, assert stops the program and returns an error. This condition is known as the Assertion Condition and error is called Assertion Error.

Syntax

assert <condition>

assert <condition>,<error message>

What is Assertion?

These are statements that assert or state a fact confidently in your program. It is a technique to check bugs in your program. Assertions are simply boolean expressions that check for a condition. If the condition is true, the program does nothing and proceeds for execution else if it is false, the program stops and throws an error. This error is called assertion error and it can only be raised when there is a bug in the program.

For example, while writing a division function, you're confident the divisor shouldn't be zero, you assert divisor is not equal to zero.

Two ways to use assert

In Python, we can use assert statement in two different ways-

Example: Using assert without Error Message

The below assert statement has a condition and the condition is false. The program returns an Assertion Error as we passed an empty list mark1 to the assert statement.

def avg(marks):
    assert len(marks) != 0
    return(sum(marks)/len(marks))

mark1 = []
print("Average of mark1:",avg(mark1))


Traceback (most recent call last):
File "/home/693a2ebeb25e22f983c3ed86a5c54b2b.py", line 6, in <module>
print("Average of mark1:",avg(mark1))
File "/home/693a2ebeb25e22f983c3ed86a5c54b2b.py", line 2, in avg
assert len(marks) != 0
AssertionError

Example: Using assert with an error message

The below assert statement returns an optional error message instead of returning an Assertion Error. The below code passed a non-empty list mark2 and also an empty list mark1 to the avg() function and we got output for the mark2 list. The assert condition was satisfied by the mark2 list and the program continues to run. But, mark1 doesn't satisfy the condition and gives an error message.

def avg(marks):
    assert len(marks) != 0,"List is empty."
    return sum(marks)/len(marks)

mark2 = [55,88,78,90,79]
print("Average of mark2:",avg(mark2))

mark1 = []
print("Average of mark1:",avg(mark1))


Runtime Errors:
Traceback (most recent call last):
File "/home/cda092f6a4546ab936c4ad76bb6543bc.py", line 9, in <module>
print("Average of mark1:",avg(mark1))
File "/home/cda092f6a4546ab936c4ad76bb6543bc.py", line 2, in avg
assert len(marks) != 0,"List is empty."
AssertionError: List is empty.
Output:
Average of mark2: 78.0

Why we use assert in Python?

  1. We use assert for checking the outputs of the functions.
  2. We use assert as a debugging tool for testing the code. The error can only be raised when there is a bug in the code.
  3. We use assert for checking the values of arguments.
  4. We use assert for checking the valid input.

Real-world Example of assert

Let us assume that a person is developing an online store using the Python programming language. He wants to add a discount coupon component to the system. The below code has a discount() function to add discount coupons to the system. The developer has used assert the statement in the discount() function to guarantee that discounted prices cannot be less than $0 and cannot be more than the original price of the product. When we check the working of the assert statement, it came out to be true as it prints the discounted value of the table. But, when we tried a false condition, the assert statement returns an Assertion Error.

Therefore, using the assert statement while developing an online store, the programmer finds it easy to debug by looking at the traceback.

def discount(prod, dis):
    
    price = int(prod['price'] * (1.0 - dis))
    assert 0 <= price <= prod['price']
    return price
    
table = {'name': 'Mango Wood Table', 'price': 14900}

#returns true
print(discount(table, 0.25))

#returns false
print(discount(table, 2.0))


Runtime Errors:
Traceback (most recent call last):
File "/home/cfdc17a71560bc424821386c1e8d5f73.py", line 10, in <module>
print(discount(table, 2.0))
File "/home/cfdc17a71560bc424821386c1e8d5f73.py", line 4, in discount
assert 0 <= price <= prod['price']
AssertionError
Output:
11175

Conclusion

In this article, we learned some different ways to use the assert keyword in Python. We also discussed Assertion conditions and errors. We also talked about a real-world example.