assert Assertion
Last updated: 2026-09-22
assert Assertion
assert expression[, msg] raises AssertionError when expression is false; disabled with -O.
| Category | Keywords & Statements |
|---|---|
| Kind | Keyword / Statement |
| Python Version | all |
📝 Syntax
assert expression[, msg]
▶ Example
Edit the code, press Run, and see the result in the output panel:
Output:
assert: must be positive
💡 Related Cases
More case studies coming soon — check back later.
❓ FAQ
QWhat happens when an `assert` fails?
AIt raises `AssertionError` and interrupts the program (unless caught). You can add a message: `assert x > 0, 'x must be positive'`, and on failure that message is shown in the exception.
QCan I use `assert` for parameter validation?
ANot recommended. When running with `python -O`, `assert` statements are removed entirely, so the validation silently disappears. For validation of user input and business logic, use formal exceptions like `if` + `raise ValueError`.
QWhat is the difference between `assert` and `if`?
A`assert` expresses «this is assumed to always hold; if not, it is a bug» and is a checking tool for development and testing. `if` is normal flow control. Do not hinge critical logic on `assert` in production code.