Robert Johns | 10 Feb, 2025
Fact checked by Jim Markus

Python Assert Statement | Docs With Examples

The Python assert statement is a debugging tool used to check conditions in your Python code.

If the condition evaluates to False, the program raises an AssertionError. It’s a great way to catch bugs early and ensure your Python code behaves as expected.

Basic Syntax

The assert statement follows this syntax:

assert condition, optional_message
  • condition: The expression to evaluate.
  • optional_message: (Optional) A message displayed if the assertion fails.

When to Use assert

  • Debugging: Validate assumptions while developing code.
  • Checking function inputs: Ensure function arguments meet expected conditions.
  • Validating results: Confirm expected outputs before continuing execution.

Common Examples

1. Basic Assertion

x = 10
assert x > 0
print("x is positive")

Explanation: Since x > 0 is True, the program runs without errors.

Output:

x is positive

2. Assertion Failure

x = -5
assert x > 0, "x must be positive"

Explanation: Since x > 0 is False, Python raises an AssertionError with the provided message.

Output:

AssertionError: x must be positive

3. Using assert to Validate Function Inputs

def divide(a, b):
    assert b != 0, "Denominator must not be zero"
    return a / b

print(divide(10, 2))  # Works
print(divide(5, 0))   # Raises AssertionError

Explanation: The assert statement ensures b is not zero before performing division.

Disabling Assertions

Assertions are meant for debugging and can be disabled in production by running Python with the -O (optimize) flag:

python -O script.py

Explanation: When optimization is enabled, Python removes all assertions from the code.

Key Takeaways

  • assert helps catch errors early by validating conditions in your Python projects.
  • If an assertion fails, Python raises an AssertionError with an optional message.
  • Assertions can be disabled in optimized (-O) mode.
  • They should not be used for error handling in production—use exceptions instead.

Practice Exercise

Here's a simple challenge, write a function in your Python editor that takes a list and asserts that it's not empty before returning the first element:

def get_first_element(lst):
    assert len(lst) > 0, "List must not be empty"
    return lst[0]

print(get_first_element([1, 2, 3]))  # Works
print(get_first_element([]))  # Raises AssertionError

Wrapping Up

The assert statement is a powerful debugging tool that ensures expected conditions hold true in your code. While useful during development, it should be used cautiously in production. Mastering assert helps you write more reliable and bug-free Python programs. Happy coding!

By Robert Johns

Technical Editor for Hackr.io | 15+ Years in Python, Java, SQL, C++, C#, JavaScript, Ruby, PHP, .NET, MATLAB, HTML & CSS, and more... 10+ Years in Networking, Cloud, APIs, Linux | 5+ Years in Data Science | 2x PhDs in Structural & Blast Engineering

View all post by the author

Subscribe to our Newsletter for Articles, News, & Jobs.

I accept the Terms and Conditions.

Disclosure: Hackr.io is supported by its audience. When you purchase through links on our site, we may earn an affiliate commission.

In this article

Learn More

Please login to leave comments