Skip to content
Tutorials Center
My learning

Topics

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.

Python
if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
else:
    grade = "C"

Try it

Python Branches and truthiness

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.

Python Conditional expressions and mistakes

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

Python
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:, not if len(items) > 0: or if items == True:. Compare to None with is, and test explicit zero with x == 0, since if x: treats None and 0 alike.
  • Chained comparisons read naturally: 0 < x < 10.
  • Short-circuiting: in if a and b, b is only evaluated when a is truthy, so if obj and obj.ready: is safe.
  • A condition does not create a scope. Names assigned inside an if block remain visible afterwards, and are unbound if the branch never ran.
  • Prefer elif over nested if/else and early returns over deep nesting. For many equal-value comparisons consider a dictionary lookup or match.
  • A block cannot be empty. Use pass or ... as a placeholder.
  • Common mistakes: = instead of == (a SyntaxError), x == 1 or 2 (always true), mixing tabs and spaces, and forgetting the colon.