Python If Else

Tutorial 14 of 65 · pythondeck.com Python course

Conditional execution uses if, elif and else. The condition is any expression evaluated for truthiness. A ternary expression a if cond else b picks between two values inline. Python 3.10+ adds structural pattern matching with match/case.

Conditional statements branch execution based on boolean tests. They translate business rules into code: validation, error paths, and feature flags all start with if. Readable branching reduces support tickets when operators must reason about production behavior.

Python uses indentation for blocks—no braces—so aligning elif and else with the matching if is mandatory for correct structure.

Forms: if, elif, else; ternary: x if cond else y.

Conditions are expressions evaluated for truthiness, not only explicit booleans.

Use elif chains for mutually exclusive cases; separate ifs when cases overlap.

pass is a no-op placeholder where syntax requires a body.

Match statement match/case (3.10+) handles structural pattern matching.

Guard clauses: early return or continue reduce nesting.

Deep nesting hurts readability—refactor with early returns or extract functions. Ternary expressions fit simple choices; nested ternaries are hard to read.

Pattern matching can replace long isinstance chains when dispatching on types or shapes.

Keep conditions side-effect free; beyond two nesting levels, use dispatch dicts or match/case.

Using = instead of == in conditions (SyntaxError or accidental assignment in walrus only).

Empty if blocks without pass, causing IndentationError.

Checking if len(x) > 0 instead of if x: for sequences (unless zero is ambiguous).

Long elif chains without default else—uncaught cases fail silently.

Handle edge cases first with guard clauses, then the happy path.

Keep conditions readable—extract complex predicates to named variables.

Prefer elif over cascading unrelated ifs when branches are exclusive.

Document what the final else does when it is not obvious.

Replace boolean flags like found = False loops with any() when searching sequences.

Re-read the examples below with these ideas in mind; change variable names and inputs to match your own project.

The program below demonstrates if/elif/else. Read the comments on each line, run the code, then change names or values to see how the output shifts.

# Example: if/elif/else
# Run in the REPL or save as a .py file and execute with python.
score = 82
if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
else:
    grade = "C"
print(grade)

This sample walks through ternary in a small, runnable script. Paste it into the REPL or save it as a .py file before you continue to the next block.

# Example: Ternary
# Run in the REPL or save as a .py file and execute with python.
n = 7
parity = "even" if n % 2 == 0 else "odd"
print(parity)

Here is a hands-on illustration of match/case. Follow the inline comments first; only then execute the snippet and compare the result with what you expected.

# Example: match/case
# Run in the REPL or save as a .py file and execute with python.
def describe(x):
    match x:
        case 0: return "zero"
        case int() if x > 0: return "positive int"
        case [a, b, *_]: return f"list starting {a},{b}"
        case _: return "something else"

print(describe(0), describe(5), describe([1,2,3]))

The program below demonstrates elif chain. Read the comments on each line, run the code, then change names or values to see how the output shifts.

# elif picks the first matching branch after if
temp_c = 31  # Celsius reading
if temp_c >= 35:  # heat wave threshold
    level = "extreme"  # assign human label
elif temp_c >= 28:  # warm day
    level = "hot"  # second branch
elif temp_c >= 20:  # mild
    level = "warm"  # third branch
else:  # cool or cold
    level = "cool"  # fallback branch
print(level)  # hot for 31C
status = "ok" if temp_c < 40 else "alert"  # conditional expression
print(status)  # ok

This sample walks through guard clauses in a small, runnable script. Paste it into the REPL or save it as a .py file before you continue to the next block.

# Early returns flatten nested logic in functions
def divide(a, b):  # divide two numbers safely
    if b == 0:  # guard invalid denominator
        return None  # signal failure without exception
    return a / b  # happy path

print(divide(10, 2))  # 5.0
print(divide(3, 0))  # None
values = [1, 2, 0, 4]  # list containing zero
result = [divide(10, x) for x in values if x]  # skip falsy
print(result)  # [10.0, 5.0, 2.5]
match_mode = "strict"  # string mode flag
print("strict" if match_mode == "strict" else "relaxed")

« Python Dictionaries All tutorials Python While Loop »