assert
In Python, the assert keyword lets you create assertions to test whether a given condition is true. If the condition is false, then assert raises an AssertionError exception, optionally with a descriptive error message. Assertions are sanity checks into your code that help you identify bugs during development.
Python assert Keyword Examples
Here’s a quick example to illustrate how to use the assert keyword:
Python
>>> x = 5
>>> y = 10
>>> assert x < y, "x is not less than y"
In this example, the condition x < y is true, so assert passes without raising an error. If x had been greater than or equal to y, the assert would have raised an error:
Python
>>> x = 15
>>> assert x < y, "x is not less than y"
Traceback (most recent call last):
...
AssertionError: x is not less than y
Because x is greater than y, the assertion fails and raises an AssertionError exception with the specified message.
Python assert Keyword Use Cases
- Quickly verifying assumptions made in your code during debugging
- Ensuring that your program is working as expected during development by inserting sanity checks
- Validating that certain conditions hold true during code testing