Conditional Statements in Python

Module 2 • Session 09 • Allocation: 1 Contact Hr

if-elif-else Short-Circuiting Ternary Operator Match-Case

Conditional statements control the execution flow of a program based on dynamic runtime evaluation. Python uses indentation blocks instead of curly braces {} to group statements, yielding clean, readable decision trees.

1. The Core Decision Chain: `if`, `elif`, `else`

Python evaluates conditions top-to-bottom. The first block whose expression evaluates to a truthy value is executed, while all subsequent branches are skipped entirely.

score = 85 if score >= 90: grade = "A" elif score >= 80: grade = "B" elif score >= 70: grade = "C" else: grade = "F" print(f"Final Grade: {grade}") # Output: Final Grade: B

2. Chained Conditions & Short-Circuit Evaluation

Combine multiple relational expressions using logical operators (and, or, not). Python optimizes execution with short-circuit evaluation:

  • A and B: If A evaluates to False, B is never checked.
  • A or B: If A evaluates to True, B is never checked.
Defensive Programming Guard: Use short-circuit evaluation to inspect safety conditions before performing unsafe operations (e.g., checking if an object is non-null before referencing its attributes).
data_list = [10, 20, 30] # Safe check: data_list is non-empty before accessing index 0 if len(data_list) > 0 and data_list[0] > 5: print("Valid data set with positive lead value.") # Membership checking with 'in' and 'not in' role = "admin" allowed_roles = ["admin", "superuser", "editor"] if role in allowed_roles: print("Access Granted")

3. Single-Line Ternary Expressions

For simple assignment branching based on a condition, Python offers a ternary operator inline construct: value_if_true if condition else value_if_false.

age = 20 status = "Adult" if age >= 18 else "Minor" print(f"User Status: {status}") # Output: User Status: Adult # Nested Ternary (Use sparingly for readability) number = -5 category = "Positive" if number > 0 else ("Negative" if number < 0 else "Zero") print(f"Number Category: {category}") # Output: Number Category: Negative

4. Structural Pattern Matching (`match-case`)

Introduced in Python 3.10, the match-case statement replaces lengthy if-elif-else branches when matching variable values against complex structural patterns.

Pattern Syntax Description Example Usage
case value: Exact literal match case 200: return "OK"
case val1 | val2: OR pattern matching multiple values case 401 | 403: return "Forbidden"
case _: Wildcard catch-all fallback (equivalent to else) case _: return "Unknown Error"
case pattern if guard: Pattern with conditional guard condition case [x, y] if x == y: return "Diagonal"
def handle_http_status(status_code): match status_code: case 200 | 201: return "Success" case 400 | 404: return "Client Error" case 500 | 502 | 503: return "Server Error" case _: return "Unhandled HTTP Status Code" print(handle_http_status(404)) # Output: Client Error
Avoid Deep Nesting: Deeply nested if blocks increase cyclomatic complexity and reduce code maintainability. Flatten complex branches by returning early or refactoring logic into helper functions.

šŸ‹ļø Try It Yourself: Practice Challenges

Challenge 1: Leap Year Validator

Write a script that evaluates whether a given year is a leap year using chained boolean rules (divisible by 4, except if divisible by 100, unless also divisible by 400).

Challenge 2: Multi-Tier Tax Calculator

Compute income tax using progressive tier rates ($0-$10k @ 0%, $10k-$50k @ 10%, >$50k @ 20%) using cleanly structured if-elif-else statements.

Challenge 3: Command Dispatcher via Match-Case

Build an interactive command parser using match-case that parses commands like "start", "stop", "pause", or fallbacks for unknown options.

⚔ Interactive Sandbox (Control Flow Engine)
Console Output:
Click "Run Code" above to execute interactive conditional scripts...

šŸ“ Knowledge Check Quiz

1. What happens during short-circuit evaluation of `False and print("Hello")`?
2. What is the correct syntax for a single-line ternary expression in Python?
3. In a Python `match-case` block, which pattern serves as the default fallback?
Advertisement
Horizontal Ad Banner Slot (728x90 / Responsive)