if Conditional

Last updated: 2026-09-22

if Conditional

if selects a branch by a boolean condition; pair with elif and else.

CategoryKeywords & Statements
KindKeyword / Statement
Python Versionall

📝 Syntax

if condition:
    block
[elif condition:
    block]*
[else:
    block]

▶ Example

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

Output:

positive
More case studies coming soon — check back later.

❓ FAQ

QI wrote `if` and `elif`, and both conditions are true, so why does only one branch run?
A`if`/`elif` is evaluated top to bottom; once it hits the first true branch it stops checking the rest. If you want several conditions to be checked independently, write several separate `if` statements instead of `elif`.
QDoes the condition after `if` need parentheses?
ANo. In Python the condition goes right after `if` and must end with a colon, e.g. `if x > 0:`. Remember that equality is tested with `==`; a single `=` is assignment and raises `SyntaxError`.
QIn `if x:`, when is `x` truthy?
APython uses «truthiness» of `x` as the condition: `0`, `0.0`, empty strings, empty lists, empty dicts, `None` and so on are falsy; everything else is truthy. So `if x:` is equivalent to «x is non-empty / non-zero / not None».
QWhy does `IndentationError` occur when there is no statement under `if`?
ABecause Python uses indentation to delimit code blocks, `if` must be followed by at least one indented statement. If you are not ready to write logic yet, put a `pass` placeholder.
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%

🙏 帮我们做得更好

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

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