Python Reference ยท Statements and Keywords
The if, elif and else statements
Reference for Python's if, elif and else statements: syntax, truthiness, nested and chained conditions, the conditional expression and common mistakes.
The if statement runs a block of code only when a condition is true. You can add any number of elif ("else if") branches and one final else branch. Python evaluates the conditions from top to bottom and runs the first block whose condition is true; the rest are skipped.
Blocks are defined by indentation, and every header ends with a colon. The condition can be any expression, not just a Boolean: Python tests its truthiness.
if score >= 90: grade = "A" elif score >= 80: grade = "B" else: grade = "C"
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Syntax
if condition: ... elif other_condition: ... else: ...
| Part | Description |
|---|---|
condition |
Any expression. It is converted to a Boolean by truthiness. |
elif |
Optional and repeatable. Tested only if all earlier conditions were false. |
else |
Optional, at most once, and last. Runs when nothing above matched. |
Conditional expression (an expression, not a statement): value_if_true if condition else value_if_false.
Usage notes
- Falsy values are
False,None, zero of any numeric type, and empty strings, lists, tuples, dicts, sets and ranges. Everything else is truthy. Instances of your own classes are truthy unless they define__bool__or__len__. - Write
if items:, notif len(items) > 0:orif items == True:. Compare toNonewithis, and test explicit zero withx == 0, sinceif x:treatsNoneand0alike. - Chained comparisons read naturally:
0 < x < 10. - Short-circuiting: in
if a and b,bis only evaluated whenais truthy, soif obj and obj.ready:is safe. - A condition does not create a scope. Names assigned inside an
ifblock remain visible afterwards, and are unbound if the branch never ran. - Prefer
elifover nestedif/elseand early returns over deep nesting. For many equal-value comparisons consider a dictionary lookup ormatch. - A block cannot be empty. Use
passor...as a placeholder. - Common mistakes:
=instead of==(aSyntaxError),x == 1 or 2(always true), mixing tabs and spaces, and forgetting the colon.
Related
match,pass,while,for- Truthiness, comparison operators, logical operators
- Lessons: if statements, Booleans