Use of assert Statement in Python



In Python, the assert statement is used for debugging purposes. It tests whether a condition in your program returns True, and if not, it raises an AssertionError. This helps you catch bugs early by verifying that specific conditions are met while the code is executing.

Understanding the Assert Statement

The assert statement is used to verify that a given condition is true during execution. If the condition evaluates to False, the program stops and throws an AssertionError, optionally displaying a message.

Example: Assertion without a message

In this example, we are asserting that 5 is greater than 3, which is true, so nothing happens -

assert 5 > 3
print("Assertion passed.")

The output is -

Assertion passed.

Using assert when the Condition Fails

If the condition in an assert statement is false, it raises an AssertionError and stops the program. This is useful for identifying faulty logic.

Example: Failing assertion

In this example, we are asserting a condition that is false, which results in an AssertionError -

assert 2 > 3
print("This line won't execute.")

The output is -

Traceback (most recent call last):
  ...
AssertionError

Adding a message to assert

You can provide a custom error message with the assert statement to make debugging easier when an assertion fails.

Example: Assertion with custom message

In this example, we are using a custom message to clarify why the assertion failed -

assert 1 == 2, "Values are not equal"

The output is -

Traceback (most recent call last):
  ...
AssertionError: Values are not equal

Using assert in functions

Assertions can be added to functions to make sure they receive valid input or return expected results during development.

Example: Using assert for input validation

In this example, we are asserting that a parameter passed to a function is not negative -

def square_root(x):
   assert x >= 0, "Input must be non-negative"
   return x ** 0.5

print(square_root(9))

The output is -

3.0

Disabling assert statements

Python allows you to disable all assert statements globally using the "- O" (optimize) flag when running the script. This is helpful in production environments.

To disable all assert statements in your Python code, follow these steps -

  • Save your Python code in a file, for example, assert.py.
  • Use the -O flag while executing the script:
python -O script.py
  • This will completely skip all assert statements in the script.
  • Example: Skipping assert with Optimization

    In the following example, the assertion will raise an error if run normally. But if executed with the -O flag, the assertion is ignored, and the remaining code continues to execute -

    # This assertion is skipped when run with: python -O script.py
    assert False, "This will not raise an error if run with -O"
    
    print("Assert ignored due to optimization.")
    

    Following is the output obtained -

    Assert ignored due to optimization.
    

    When to use assert

    The assert statement is helpful during development and testing to catch bugs early. It should not be used for regular error handling in production. Instead, use proper if conditions and exception handling.

    Example: Avoiding assertions for production checks

    In this example, we are using a standard if condition instead of an assert to check for valid input -

    def divide(a, b):
       if b == 0:
          raise ValueError("Cannot divide by zero")
       return a / b
    
    print(divide(10, 2))
    

    The output is -

    5.0
    
    Updated on: 2025-05-15T13:57:00+05:30

    287 Views

    Kickstart Your Career

    Get certified by completing the course

    Get Started
    Advertisements