In Python, The `assert` statement is used as a debugging aid. It tests a condition, and if the condition is "False", it raises an "AssertionError" exception with an optional error message.
It's commonly used to check for conditions that should always hold "True" in our code.
assert condition, "optional message"
condition: A boolean expression that you expect to be "True". If the condition evaluates to "False", an "AssertionError" exception is raised.
message (optional): An optional message to be included in the AssertionError exception. It provides additional information about why the assertion failed.
x = 12 assert x == 12 # Condition is True, so no error is raised y = 10 assert y == 7 # Condition is False, so AssertionError is raised
x = 30 assert x == 6, "x should be equal to 6" # Raises AssertionError with the specified message #Output: AssertionError: x should be equal to 5
Validating Assert condition within functions.
def divide(a, b): assert b != 0, "Value can not be divide by zero" return a / b result = divide(50, 4) # Print the result print(result) # Output: 12.5
Checking with 0 value.
def divide(a, b): assert b != 0, "Value can not be divide by zero" return a / b result = divide(50, 0) # Print the result print(result) # Output: AssertionError: Value can not be divide by zero
Use assert to check for conditions that you expect to be true during development and testing.
Don't use assert for data validation in production code because assertions can be disabled with the -O flag or in optimized builds.
If we want to handle potential errors gracefully in production code, use proper exception handling mechanisms like try-except blocks.
Assertions can be disabled globally by running the Python interpreter with the "-O" (optimize) flag or using the "-oo" flag to remove docstrings and assert statements.
python -O script.py
When assertions are disabled, all assert statements are ignored, and the code runs as if they weren't there.
It's essential to use assertions only for debugging purposes and not rely on them for production code behaviour.