Assert statement in Python
The assert statement is a debugging and testing tool used to check conditions in your code.
- If the condition is True → the program continues normally.
- If the condition is False → Python raises AssertionError.
In simple terms: “Assert that this condition must be true.”
Basic Syntax
assert condition # With custom error message assert condition, "Error message if condition fails"
How assert Works (Concept)
Python
assert x > 0
This means Python checks if x > 0. If the condition is false, Python stops execution and raises an error.
Equivalent logic:
Python
if not x > 0:
raise AssertionError Example: Basic Assertion
Python
x = 10
assert x > 0 # This will pass (no error)
print("x is positive") Example: Assertion Failure
Python
x = -5
assert x > 0 # This will fail
print("This line will not execute") Output: AssertionError
Example: Custom Error Message
Python
age = 15 assert age >= 18, "User must be at least 18 years old"
Output: AssertionError: User must be at least 18 years old
Example: assert in Functions
Python
def divide(a, b):
# Ensure denominator is not zero
assert b != 0, "Denominator cannot be zero"
return a / b
print(divide(10, 2)) # Works
print(divide(10, 0)) # AssertionError