Pythonif / elif / else

if / elif / else

Conditionals let your program make decisions. Python uses if, elif, and else to branch execution based on whether an expression evaluates to something truthy or falsy. Unlike many languages, Python doesn't use curly braces or switch statements (well — it does have match, covered on its own page) — indentation alone defines which block belongs to which condition.

Basic syntax

An if statement can stand alone, or be followed by any number of elif (short for "else if") branches, and an optional final else that catches everything else. Python evaluates the conditions top to bottom and runs the first block whose condition is true — the rest are skipped.

Basic if / elif / else

Python
age = 20

if age < 13:
    category = 'child'
elif age < 20:
    category = 'teenager'
elif age < 65:
    category = 'adult'
else:
    category = 'senior'

print(category)  # adult
Nested conditionals

Conditionals can be nested inside one another when a decision depends on more than one independent question. Nesting is useful, but deeply nested if blocks are hard to read — often you can flatten them using elif, combined boolean conditions, or early return statements inside a function.

Nested if statements

Python
def classify_ticket(is_member, age):
    if is_member:
        if age < 18:
            return 'member-child-price'
        else:
            return 'member-adult-price'
    else:
        if age < 18:
            return 'guest-child-price'
        else:
            return 'guest-adult-price'

print(classify_ticket(True, 15))   # member-child-price
print(classify_ticket(False, 30))  # guest-adult-price
Conditional (ternary) expressions

When you just need to pick between two values based on a condition, a full if block is often overkill. Python's conditional expression — value_if_true if condition else value_if_false — lets you write that in a single line. It's an expression, not a statement, so it produces a value you can assign, return, or pass directly.

Ternary-style conditional expression

Python
age = 16
status = 'adult' if age >= 18 else 'minor'
print(status)  # minor

# Works anywhere an expression is expected
numbers = [1, 2, 3, 4, 5, 6]
labels = ['even' if n % 2 == 0 else 'odd' for n in numbers]
print(labels)  # ['odd', 'even', 'odd', 'even', 'odd', 'even']
Truthy and falsy values (quick recap)

Every object in Python has an inherent boolean value when used in a condition. You don't need to explicitly compare to True or False — Python will coerce automatically. The falsy values worth remembering: 0, 0.0, "" (empty string), [], {}, (), set(), and None. Everything else is truthy.

Falsy value checks

Python
values = [0, 1, '', 'hello', [], [1, 2], {}, None]

for v in values:
    if v:
        print(f'{v!r} is truthy')
    else:
        print(f'{v!r} is falsy')

# 0 is falsy
# 1 is truthy
# '' is falsy
# 'hello' is truthy
# [] is falsy
# [1, 2] is truthy
# {} is falsy
# None is falsy
Membership and chained comparisons

Python conditions read naturally when combined with the in membership operator or with chained comparisons. Instead of writing x > 0 and x < 10, you can write 0 < x < 10 directly — Python evaluates chained comparisons the way you'd read them in math class.

Membership and chained comparisons

Python
x = 5

if x in (1, 2, 3):
    print('x is a small number')
elif 0 < x < 10:
    print('x is a single digit, but not 1-3')
else:
    print('x is something else')
# x is a single digit, but not 1-3

fruit = 'apple'
if fruit in ('apple', 'banana', 'cherry'):
    print(f'{fruit} is in stock')
Avoid comparing to True / None with ==
A common anti-pattern from other languages is writing `if x == True:`. Since `x` is already a boolean expression's result (or something Python can evaluate truthily), just write `if x:`. Similarly, prefer `if x is None:` over `if x == None:` — `is` checks identity, which is the correct and faster way to test for `None`, and it avoids surprises with custom `__eq__` implementations.

Bad vs good style

Python
# Bad
if x == True:
    ...
if x == None:
    ...

# Good
if x:
    ...
if x is None:
    ...
Quick reference
  • if / elif / else branches run top to bottom; only the first true branch executes.

  • elif is optional and repeatable; else is optional and must come last.

  • x if cond else y is a ternary expression, usable anywhere a value is expected.

  • 0, "", [], {}, (), and None are falsy; everything else is truthy.

  • in tests membership; chained comparisons like 0 < x < 10 read naturally.

  • Prefer if x: over if x == True:, and if x is None: over if x == None:.