Conditionals
Conditionals choose which block of code runs by testing a condition. Python uses if, elif, and else, plus a one-line conditional expression when you need a value rather than a statement.
Detailed Explanation
A program that always runs the same lines cannot react to input. Conditionals are how you say "if the cart is empty, show the empty state; if the user is a guest, hide checkout; otherwise take payment". Python writes that as a chain of if / elif / else blocks, indented under each test.
Only one block in a chain runs. Python evaluates tests from the top. The first true condition wins, and the rest are skipped. elif is not a second independent if. That difference matters when two conditions can both be true: put the more specific test first, or you will never reach the second.
There is no switch statement in older Python. The replacement for a long chain of equality tests is often a dictionary of callables, or the match statement added in 3.10. Use if when the tests are ranges, combinations, or predicates. Use match when you are destructuring a shape.
The condition can be any object. Python uses truthiness: empty containers and zeros are false, everything else is true. When zero is a legal value, write the comparison you mean (if retries is None, if retries == 0) instead of if retries.
The conditional expression a if cond else b produces a value. It is for choosing between two expressions, not for hiding a side-effecting block. status = "open" if seats else "sold-out" is readable. A nested chain of ternary expressions is not. When the branches need more than one expression, use a statement.
if is a statement and cannot sit where a value is required. You cannot write return if ready: payload. You can write return payload if ready else None. That split — statement versus expression — is the same distinction as lambda versus def.
Indentation is the block. There are no braces. A missing indent is a SyntaxError. A wrong indent is a silent logic bug: the line you thought was inside the if runs every time. Keep bodies short, and do not put an else several screens below its if.
Code Examples
seats = 3
member = True
if seats <= 0:
status = "sold-out"
elif member:
status = "member-rate"
else:
status = "standard"
print(status) # member-rate
# Conditional expression: choose a value, not a block.
label = "open" if seats else "sold-out"
print(label) # open# A dict of callables replaces a long equality chain.
def ship_standard(order_id: str) -> str:
return f"{order_id}: ground"
def ship_express(order_id: str) -> str:
return f"{order_id}: overnight"
handlers = {"standard": ship_standard, "express": ship_express}
method = "express"
print(handlers[method]("ORD-9")) # ORD-9: overnightCommon Gotchas
A second `if` is not `elif`
two separate `if` statements can both run. `elif` is exclusive. Use `elif` when the cases are alternatives.
Assignment is not allowed in `if`
`if user = fetch():` is a `SyntaxError`. Use `:=` if you need to assign and test in one line, or assign on the line above.
`else` belongs to the nearest `if`/`for`/`while`/`try`
a misplaced `else` after a loop is a different feature. Read the indent before you assume it is the `if`'s else.