Last modified: Oct 28, 2026
Python Assert Statement Explained
The assert statement in Python is a powerful tool for debugging. It checks if a condition is true. If the condition is false, it raises an AssertionError. This helps developers catch bugs early in development.
How Does Assert Work?
The syntax is simple:assert condition, optional_message
If the condition evaluates to True, nothing happens. If it evaluates to False, Python stops execution and shows an error.
Example 1: Basic Usage
# Check if a number is positive
number = 5
assert number > 0
print("Number is positive")
Number is positive
Example 2: Adding a Custom Message
# Check age with custom message
age = 15
assert age >= 18, "User must be at least 18 years old"
print("Access granted")
AssertionError: User must be at least 18 years old
Why Use Assert?
Assert helps validate assumptions. It acts as a safety net. Developers use it to check function inputs, outputs, and intermediate values. It improves code reliability.
Example 3: Validating Function Input
def divide(a, b):
# Ensure divisor is not zero
assert b != 0, "Cannot divide by zero"
return a / b
result = divide(10, 2)
print(result)
5.0
Example 4: Checking Return Values
def get_positive_number():
value = -5
assert value > 0, "Value should be positive"
return value
get_positive_number()
AssertionError: Value should be positive
Common Mistakes with Assert
Avoid using assert for data validation in production. It can be disabled with the -O flag. Use exceptions instead for critical checks.
Example 5: Disabled Assert
# This assertion will be ignored when running with -O flag
x = -1
assert x >= 0, "x must be non-negative"
print("No error shown with -O flag")
No error shown with -O flag
Assert vs Raise
Both raise errors. But assert is for debugging. Raise is for handling expected errors. Choose wisely based on context.
Example 6: Using Raise Instead
def check_age(age):
if age < 18:
raise ValueError("Age must be 18 or above")
return True
check_age(16)
ValueError: Age must be 18 or above
Best Practices
- Use assert for debugging, not validation
- Add meaningful messages to assertions
- Keep assertions simple
- Do not use side effects in assertions
Example 7: Side Effects in Assert
# Bad practice - side effect in assert
data = []
assert data.append(1) == 1
print(data)
[1]
Real-World Example
Here’s a practical example using Generate Test Data with Faker in Python to demonstrate how assert validates generated data.
from faker import Faker
fake = Faker()
# Generate fake user data
name = fake.name()
email = fake.email()
# Validate generated data
assert "@" in email, "Invalid email format"
assert len(name) > 0, "Name cannot be empty"
print(f"Valid user: {name}, {email}")
Valid user: John Doe, [email protected]
Conclusion
The assert statement is a helpful feature for catching bugs early. It improves code quality. Remember to use it appropriately. Avoid relying on it for production validation. Pair it with proper testing strategies.
For more Python tips, check out Python Pass Statement Explained and Python If Else Statements: A Beginner Guide. Also explore Python Global and Local Variables to understand variable scope better.