assert Assertion

Last updated: 2026-09-22

assert Assertion

assert expression[, msg] raises AssertionError when expression is false; disabled with -O.

CategoryKeywords & Statements
KindKeyword / Statement
Python Versionall

📝 Syntax

assert expression[, msg]

▶ Example

Edit the code, press Run, and see the result in the output panel:

Output:

assert: must be positive
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.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏