if
Python tests truthiness, not "== True": 0, empty strings, empty containers and None all count as false. elif chains tests, and only the first true branch runs.
if condition: body
if test1: first elif test2: second else: fallback
x = a if condition else b
Demo
value = 0 verdict = "falsy" if value: verdict = "truthy" verdict
In the if tab, the condition is not compared with True — Python asks bool(value). Zero of any number type and the empty string are false; a single space and the text "False" are non-empty strings, so they are true. In the if / elif / else tab, 90 gets an A because the >= 90 test comes first; every later elif is skipped once one branch has run. In the x if c else y tab, the upper bound 10 is excluded because the chain reads n < 10.
Syntax slots
| Name | Type | Required | Description |
|---|---|---|---|
| condition | expression | yes | Any value. Python calls bool() on it: 0, 0.0, "", [], {}, set(), None and False are false; almost everything else is true. |
| body | block | yes | Runs when the condition is truthy. Must not be empty — write pass for a placeholder. |
| elif | block | no | Any number of further tests. Checked top to bottom only while every test above was false; the first true one wins. |
| else | block | no | Runs when no if / elif test was true. At most one, always last. |
Common patterns
def area(w, h): if w < 0 or h < 0: raise ValueError("negative size") return w * h
def first(items): if not items: return None return items[0]
def is_weekend(day): return day in {"sat", "sun"}
def label(n): return "item" if n == 1 else "items"
Examples
Pitfalls
answer = 'no' if answer == 'y' or 'yes': print('accepted')
answer = 'no' if answer in ('y', 'yes'): print('accepted') else: print('rejected')
n = 95 hits = [] if n > 50: hits.append('pass') if n > 90: hits.append('top') hits
n = 95 if n > 90: grade = 'top' elif n > 50: grade = 'pass' grade
discount = 0 if not discount: discount = 10 discount
discount = 0 if discount is None: discount = 10 discount
compile('if x = 5:\n pass', '<demo>', 'exec')
x = 5 if x == 5: print("five")
When to use
- Choosing between actions based on a condition
- Guard clauses that reject bad input early
- Picking one of two values inline with a if c else b
- Long elif chains mapping values to values → a dict lookup
- Matching on the shape of data (lists, dicts, objects) → match (3.10+)
- Returning a bool from a test → return the test itself, not if ...: return True
Notes
FAQ
It is spelled elif. You can write else: followed by an indented if, but that nests one level deeper for each test; elif keeps the whole chain flat. There is no switch statement — use elif, a dict lookup, or match (3.10+).