7. Simple statements


Introduction

Python assertions are statements used to check whether a given condition is true or false during the execution of a program. They are primarily used for debugging and to ensure that certain conditions hold true at specific points in the code.

Syntax

An assertion in Python has the following syntax:

assert condition, message

Here, condition is the expression that is expected to be true. If the condition evaluates to False, an AssertionError is raised with an optional error message.

Usage and Debugging

Assertions help you catch logical errors during development. When an assertion fails, it indicates that something unexpected has occurred, which allows you to identify and fix the issue earlier in the development process. They are particularly useful in testing and debugging to ensure your code behaves as expected.

Example

def divide(a, b):
    assert b != 0, "Cannot divide by zero!"
    return a / b

In this example, the assert statement checks if the denominator b is not zero before performing the division. If b is zero, the assertion fails, and the error message "Cannot divide by zero!" is raised.

Disabling for Testing:

Assertions can be disabled globally when running the Python script using the -O (capital letter O) or -OO command-line options. This optimization flag disables all assert statements:

By disabling assertions, you can improve the performance of your code in production while still keeping the error-checking capability during development.

Keep in mind that it's essential to use assertions for debugging purposes, but you should not rely on them for handling exceptions or errors that are part of normal program flow. For that, you should use proper try-except blocks.