MOD-13 · Sequence #13 · Control Flow

Python If...Else & Branching

Control flow in Python relies on if, elif, and else blocks. Python does not require switch/case statements (though Python 3.10 added match/case). Understanding conditional expressions (ternary operator) enables concise branching.

Live Interactive Code Snippet (Python 3.12 CPython WASM) Open in Practice Mode →
a = 200
b = 33
status = "Greater" if a > b else "Lesser"
print(status)

Core Principles & Mental Models

1. The if-elif-else Ladder

Mutually Exclusive Evaluation

  • Conditions are evaluated sequentially from top to bottom.
  • The first condition that evaluates to Truthy executes its block, and Python skips all remaining elif and else clauses.
  • An else clause executes only if all preceding if and elif tests evaluated to falsy.
score = 85
if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
elif score >= 70:
    grade = "C"
else:
    grade = "F"
print(f"Score {score} -> Grade {grade}")
💡 Key Takeaway: Place the most specific conditions at the top of the elif ladder.

2. Conditional Expression (Ternary Operator)

Inline Expression Syntax

  • Python syntax for ternary expressions is: `x if condition else y`.
  • Unlike if statements, conditional expressions return a value and can be assigned to variables or passed to functions directly.
age = 20
status = "Adult" if age >= 18 else "Minor"
print("Status:", status)
💡 Key Takeaway: Use inline ternary expressions for simple value assignments based on a single condition.

Interactive Walkthrough Examples

Ternary Logic in List Transformations (Basic)

Using ternary expressions inside a list comprehension to normalize grades.

scores = [92, 58, 77, 85, 45]
results = ["Pass" if s >= 60 else "Fail" for s in scores]
for s, r in zip(scores, results):
    print(f"Score {s}: {r}")

Explanation: "Pass" if s >= 60 else "Fail" is evaluated for each element in the sequence.

Common Misconceptions & Exam Traps

Common Pitfall: Accidental Assignment in Conditions (SyntaxError Protection)

Python statements (assignment =) cannot be used inside expressions, preventing this classic C bug.

Buggy Code
# In C/Java: if (x = 5) compiles accidentally! In Python:
# if x = 5: raises SyntaxError: invalid syntax.
Correct Solution
x = 5
if x == 5:
    print("Equal")

Exam Trap Note: Python 3.8 introduced the walrus operator (:=) if you explicitly need assignment inside an expression.

Conceptual Knowledge Self-Check Quiz

Q1: What is the correct syntax for an inline conditional expression in Python?

  1. condition ? true_val : false_val
  2. true_val if condition else false_val
  3. if condition then true_val else false_val
  4. condition ? (true_val, false_val)

Python uses the syntax `value_if_true if condition else value_if_false`.

Algorithmic Practice Challenges

Idiomatic Best Practices

  • ✅ Avoid deeply nested if statements; refactor using guard clauses and early returns.
  • ✅ Group related boolean flags into helper functions for clarity.

All 26 Curriculum Modules