Python assert keyword

Last Updated : 11 Aug, 2026

assert keyword is used to check whether a condition is True during program execution. If the condition is True, the program continues normally. If the condition is False, Python raises an AssertionError and stops the program.

Python
age = 20
assert age >= 18
print("Eligible")

Output
Eligible

Explanation: condition age >= 18 is True, so no error is raised, and the program continues to execute the print() statement.

frame_3294
Flowchart of Python Assert Statement

Syntax

assert condition, "Error message"

Parameters:

  • condition: A Boolean expression that evaluates to True or False.
  • error_message (optional): A message displayed if the assertion fails.

Returns: does not return any value. If the condition is False, it raises an AssertionError with the optional error message.

Without an Error Message

The assert keyword allows you to provide a custom error message that is displayed when the assertion fails. This makes it easier to identify the reason for the error.

Python
a = 4
b = 0

print("The value of a / b is:")
assert b != 0, "Division by zero is not allowed."
print(a/b)

Output

The value of a / b is:
ERROR!
Traceback (most recent call last):
File "<main.py>", line 5, in <module>
AssertionError: Division by zero is not allowed.

Explanation: condition b != 0 evaluates to False because b is 0. Therefore, Python raises an AssertionError and displays the custom error message "Division by zero is not allowed." The program stops before executing the division operation.

Inside a Function

assert keyword can be used inside a function to validate input values before performing a calculation. If the condition evaluates to False, the function stops and raises an AssertionError.

Python
def calculate_area(radius):
    assert radius > 0, "Radius must be greater than 0."
    return 3.14 * radius * radius

print(calculate_area(-5))

Output

ERROR!
Traceback (most recent call last):
File "<main.py>", line 5, in <module>
File "<main.py>", line 2, in calculate_area
AssertionError: Radius must be greater than 0.

Explanation: condition radius > 0 evaluates to False because the value passed is -5. Therefore, Python raises an AssertionError with the message "Radius must be greater than 0.", and the return statement is not executed.

With Boolean Condition

assert keyword can be used with any Boolean expression. If the expression evaluates to True, the program continues executing; otherwise, it raises an AssertionError.

Python
x = 10
y = 20

assert x < y
print("x =", x)
print("y =", y)

Output
x = 10
y = 20

Explanation: condition x < y evaluates to True because 10 is less than 20. Therefore, the assertion succeeds, and the print() statements are executed.

Checking Variable Types

Verifying the data type of a variable helps ensure that the program receives valid input before performing further operations. Here, we check whether username is a string and age is an integer before printing their values.

Python
username = "David"
age = 25

assert type(username) == str
assert type(age) == int

print("Username:", username)
print("Age:", age)

Output
Username: David
Age: 25

Explanation: expressions type(username) == str and type(age) == int both evaluate to True. Therefore, the assertions succeed, and the print() statements are executed.

Checking Dictionary Values

Assertions can also be used to verify that a dictionary contains the expected values before the data is processed. Here, we verify the values stored in the product dictionary.

Python
product = { "name": "Laptop",
            "price": 50000 }

assert product["name"] == "Laptop"
assert product["price"] == 50000
print(product)

Output
{'name': 'Laptop', 'price': 50000}

Explanation: expressions product["name"] == "Laptop" and product["price"] == 50000 both evaluate to True. Therefore, the assertions succeed, and the dictionary is printed.

Validating Data

Assertions can be used to verify that data meets a required condition before it is processed. If any value fails the validation, the program stops and raises an AssertionError. Here, we check whether each product in a batch has a quality score of at least 80 before approving it.

Python
scores = [95, 88, 91, 84, 76, 89]

for i in scores:
    assert i >= 80, "Batch rejected"
    print(i, "Approved")

Output

95 Approved
88 Approved
91 Approved
84 Approved
ERROR!
Traceback (most recent call last):
File "<main.py>", line 4, in <module>
AssertionError: Batch rejected

Explanation:

  • assertion checks whether each value satisfies the condition score >= 80. The first four values pass the check and are printed.
  • When the value 76 is encountered, the condition evaluates to False, so Python raises an AssertionError with the message "Batch rejected" and stops the program

Why Use the assert Keyword?

assert keyword helps verify that a program behaves as expected during development. It allows you to detect invalid conditions early by raising an AssertionError when a condition evaluates to False. Some common uses of the assert keyword include:

  • Debugging: Detect unexpected conditions while the program is running.
  • Testing: Verify that functions and code produce the expected results.
  • Input Validation: Ensure that values satisfy required conditions before further processing.
  • Finding Errors Early: Stop program execution immediately when an invalid condition is encountered.
Comment