How to Use the assert Statement in Python?

The assert statement in Python is used during debugging to check for conditions that should always be true. If the condition evaluates to False, an AssertionError is raised.

Basic Syntax

assert condition, optional_message

Example Usage

def divide(a, b):
    assert b != 0, 'Divider cannot be zero'
    return a / b

Disabling Assertions

Assertions can be disabled globally by running Python with the -O (optimize) flag:

python -O script.py

Conclusion

The assert statement is a useful tool for debugging and ensuring code correctness. Use it to catch errors early in development.

Leave a Reply

Your email address will not be published. Required fields are marked *