Logo OnlineCBT
PYTHON Tutorial
PYTHON · LESSON 12

Conditional Patterns and match-case

Use conditional expressions, guard clauses and structural pattern matching without hiding program logic.

Level: Beginner to Advanced
Duration: ~60 Mins Deep-Dive
Updated: 26 Jul 2026

Lesson 12: Conditional Patterns and match-case

1. Introduction to Structural Pattern Matching

In Python 3.10 (released via PEP 634, PEP 635, and PEP 636), Python introduced one of its most powerful syntactic features in over a decade: Structural Pattern Matching using the match-case statement.

While developers coming from languages like C, C++, Java, or JavaScript might initially compare match-case to a traditional switch-case statement, Python's match-case is far more sophisticated. It goes beyond simple primitive value comparisons by inspecting an object's **structure, shape, type, data elements, and attributes**, binding extracted variables on the fly while performing conditional checks simultaneously.


2. Basic Syntax Structure of `match-case`

1. Core Syntax Components

A match block accepts a target expression (subject), followed by one or more case clauses representing patterns to evaluate against the subject.

# General Syntax Structure of Structural Pattern Matching:
match subject_expression:
    case pattern_1:
        # Code block executed if subject matches pattern_1
        statement_block_1
    case pattern_2:
        # Code block executed if subject matches pattern_2
        statement_block_2
    case _:
        # Wildcard fallback case (executed if no previous patterns match)
        default_statement_block
    
Soft Keywords Concept: match and case are **soft keywords** in Python. This means you can still use match or case as variable names in legacy code without breaking compatibility or raising a SyntaxError!
BASIC_MATCH_CASE.PY
http_status_code = 404

print(f"Evaluating HTTP Response Code: {http_status_code}")

match http_status_code:
    case 200:
        message = "OK: Request succeeded."
    case 301:
        message = "Moved Permanently: Resource redirected."
    case 400:
        message = "Bad Request: Client-side syntax error."
    case 404:
        message = "Not Found: Resource does not exist."
    case 500:
        message = "Internal Server Error: Unexpected failure."
    case _:
        message = "Unknown Status Code."

print("Status Explanation:", message)
OUTPUT
Evaluating HTTP Response Code: 404
Status Explanation: Not Found: Resource does not exist.

3. The Wildcard Pattern (`_`) and Fallback Logic

The underscore character (_) serves as the **Wildcard Pattern** in a match-case construct. It matches any object unconditionally without binding the matched value to a variable name.

Wildcard Placement Rule: The wildcard case case _: MUST be placed as the final case clause in a match statement. Placing case _: before other patterns causes Python to raise a SyntaxError: wildcard makes remaining patterns unreachable!

4. Combining Multiple Patterns with the OR Operator (`|`)

You can combine multiple literal patterns into a single case block using the pipe symbol (|), which acts as a logical OR pattern matching operator.

OR_PATTERN_MATCHING.PY
day_name = "Saturday"

match day_name.title().strip():
    case "Monday" | "Tuesday" | "Wednesday" | "Thursday" | "Friday":
        day_type = "Weekday (Workday)"
    case "Saturday" | "Sunday":
        day_type = "Weekend (Rest Day)"
    case _:
        day_type = "Invalid Day Name"

print(f"The day '{day_name}' is classified as: {day_type}")
OUTPUT
The day 'Saturday' is classified as: Weekend (Rest Day)

5. Conditional Guards in Patterns (`if` Clauses)

A pattern match can be restricted further by adding a **Guard clause**. A Guard is an additional Boolean expression appended to a case clause using the if keyword: case pattern if condition:.

Python first verifies if the structural pattern matches. If the pattern matches, Python then evaluates the guard's Boolean expression. The case block executes **ONLY IF both the pattern matches AND the guard evaluates to `True`**.

MATCH_GUARDS_DEMO.PY
user_account = ("premium_subscriber", 250.00)

match user_account:
    # Matches tuple structure AND verifies balance guard condition
    case ("premium_subscriber", balance) if balance >= 500.00:
        status = "VIP Access Granted with Concierge Rewards!"
    case ("premium_subscriber", balance) if balance < 500.00:
        status = "Standard Premium Access Granted."
    case ("free_tier", _):
        status = "Ad-supported Limited Access Granted."
    case _:
        status = "Account Unrecognized."

print("Account Permission Level:", status)
OUTPUT
Account Permission Level: Standard Premium Access Granted.

6. Sequence Unpacking and Data Structure Patterns

The true engineering power of match-case lies in **Sequence Pattern Unpacking**. Python can match lists, tuples, and dynamic user inputs based on their length, element types, and positional values, extracting variables directly into local scope.

SEQUENCE_UNPACKING_MATCH.PY
# Simulating CLI command line arguments received as list of strings
command_tokens = ["UPDATE", "user_profile.json", "--force"]

match command_tokens:
    case ["QUIT"]:
        print("System shutting down...")
    case ["LOAD", filename]:
        print(f"Loading data file: {filename}")
    case ["UPDATE", filename, flag]:
        print(f"Updating file '{filename}' with flag option: {flag}")
    case ["DELETE", filename]:
        print(f"Deleting target file: {filename}")
    case _:
        print("Command Unrecognized!")
OUTPUT
Updating file 'user_profile.json' with flag option: --force

Matching Variable Length Sequences (`*rest`)

Similar to list unpacking, you can use the star operator (*rest) inside a case pattern to capture leftover sequence items into a list:

STAR_PATTERN_MATCH.PY
system_log = ["ERROR", "DB_CONNECTION_FAILED", "Timeout at 10.0.0.1", "Retries: 3"]

match system_log:
    case ["INFO", *details]:
        print("Info Log Entries:", details)
    case ["ERROR", error_code, *diagnostics]:
        print(f"Critical Error Detected! Code: {error_code}")
        print("Diagnostic Output Logs:", diagnostics)
    case _:
        print("Unformatted Log Entry")
OUTPUT
Critical Error Detected! Code: DB_CONNECTION_FAILED
Diagnostic Output Logs: ['Timeout at 10.0.0.1', 'Retries: 3']

7. Comparative Matrix: `if-elif-else` vs `match-case`

  • Primary Purpose
  • General-purpose Boolean expression evaluation.
  • Structural shape, type, and value pattern matching.
  • Syntax Readability
  • Can become cluttered with repetitive elif operators.
  • Highly readable, structured, and declarative layout.
  • Variable Extraction
  • Requires explicit indexing/slicing in separate lines.
  • Automatically unpacks and binds variables inside pattern.
  • Python Version Support
  • Supported across all Python versions (1.0+).
  • Supported ONLY in **Python 3.10+**.
Feature / Dimension `if-elif-else` Ladder `match-case` Pattern Matching

8. Frequently Asked Interview Questions with Answers

Q1: How does Python's `match-case` differ fundamentally from C/Java's `switch-case`?
Answer: C/Java's switch-case tests primitive equality (integers, strings, enums) against static values with explicit fall-through behavior (requiring break keywords). Python's match-case performs **Structural Pattern Matching**—it matches data structures, list lengths, types, and sequence shapes, automatically unpacking variables while eliminating fall-through bugs without needing break.
Q2: What are "Soft Keywords" in Python, and why are `match` and `case` classified as such?
Answer: Soft keywords are keywords that are recognized as syntax tokens only inside specific contexts (such as a match-case block). Outside pattern matching blocks, match and case remain valid variable identifiers, ensuring existing legacy Python code bases do not break.
Q3: What is the role of the wildcard pattern `_` and what happens if it is misplaced?
Answer: The wildcard _ acts as a catch-all pattern that matches any subject unconditionally. It must always be placed as the final case in a match statement. Placing case _: earlier causes Python to raise a SyntaxError because subsequent case blocks become permanently unreachable.
Q4: How do Conditional Guards work in a `case` clause?
Answer: A Guard is an if condition appended to a case pattern (e.g., case [x, y] if x > 0:). Python first verifies if the structural pattern matches. If it matches, Python then evaluates the guard expression. The block executes only if both pattern matching AND guard evaluation return True.
Q5: What Python version introduced `match-case`, and how do you handle backward compatibility?
Answer: Structural Pattern Matching was introduced in Python 3.10 (via PEP 634). If an application must support legacy Python environments (< 3.10), developers must write traditional if-elif-else conditional trees instead.

9. Homework & Practical Assignments

Task 1: Lesson 12 Specific Exercise — CLI Command Dispatcher

Create a script named cli_dispatcher.py inside your lesson_12 folder using match-case:

  • Accept a command string input from the user (e.g., "MOVE NORTH 5", "SHOOT", "LOOK").
  • Clean whitespace with .strip() and convert to uppercase, then split into a list of words using .split().
  • Use match-case sequence pattern matching:
    • ["LOOK"] → Print "Inspecting surroundings..."
    • ["SHOOT"] → Print "Weapon fired!"
    • ["MOVE", direction, steps] → Cast steps to integer and print "Moving [steps] units towards [direction]."
    • case _ → Print "Unknown command string!"

Task 2: Comprehensive Review Assignment (Lessons 1 to 12 Master Project)

Project Goal: Build a complete terminal-based smart_ecom_terminal.py script that integrates all foundational concepts learned from Lesson 1 through Lesson 12.

Project Requirements Checklist:

  1. Header & Setup (Lessons 1-4): Write clear comments and docstrings. Format clean line output banner using custom sep and end parameters in print(). Follow PEP 8 variable naming standards.
  2. Variable Assignment & Data Types (Lessons 5-6): Declare product catalog items using string literals, floating-point prices, integers, and Booleans. Store store status variables.
  3. Operators & Mathematical Calculations (Lesson 7): Prompt the user for item quantity and unit price. Calculate subtotal, apply a tax rate (18%), and compute final bill using arithmetic operators (*, +) and round() or math.ceil().
  4. String Processing (Lesson 8): Prompt for customer full name and email string. Use .strip(), .title(), and .split("@") to parse email username and domain accurately.
  5. Formatted Output with f-Strings (Lesson 9): Output a clean formatted bill receipt using f-strings with currency format specifiers (:,.2f) and text alignment padding (:<15, :>10).
  6. Boolean Logic & Comparisons (Lesson 10): Evaluate eligibility for free shipping using chained comparisons and logical operators (e.g., if total >= 1000 and email_domain == "company.com").
  7. Conditional Control Flow (Lesson 11): Determine customer discount tier (Gold: 20%, Silver: 10%, Bronze: 5%) using an if-elif-else ladder.
  8. Pattern Matching (Lesson 12): Use a match-case block to inspect payment mode selection input:
    • case ["CARD", card_number] → Mask card number showing only last 4 digits (slicing) and approve payment.
    • case ["UPI", upi_id] if "@" in upi_id → Validate UPI domain format and approve.
    • case ["CASH"] → Confirm cash on delivery.
    • case _ → Reject transaction as invalid payment method.

10. File & Workspace Directory Structure

Standard Course Workspace Layout:

Ensure all exercise files are stored inside their corresponding lesson directories:

python_mastery_course/
│
├── lesson_01/
├── lesson_02/
├── lesson_03/
├── lesson_04/
├── lesson_05/
├── lesson_06/
├── lesson_07/
├── lesson_08/
├── lesson_09/
├── lesson_10/
├── lesson_11/
│
└── lesson_12/
    ├── basic_match_case.py
    ├── or_pattern_matching.py
    ├── match_guards_demo.py
    ├── sequence_unpacking_match.py
    ├── star_pattern_match.py
    ├── cli_dispatcher.py
    └── smart_ecom_terminal.py  <-- (Lesson 1-12 Master Review Project)
        

11. What We Will Learn Next

Next Up: Lesson 13 — for Loops, range and Iteration

Now that you master decision-making, conditional logic, and structural pattern matching, we will enter the world of automated repetition and loops.

In the next lesson, we will cover:

  • Introduction to Iteration and the for loop execution model.
  • Iterating over sequence collections (Strings, Lists, Tuples, Dictionaries).
  • Deep dive into the range(start, stop, step) sequence generator function.
  • Calculating accumulators, running totals, and loop counters.
  • Understanding sequence unpacking inside loop headers (e.g., for key, value in dictionary.items():).

📝 Live Lesson Practice

HTML/CSS JavaScript Python C++ C PHP
⌨️ Practice Inputs (लाइव इनपुट भरें) (खाली होने पर RED, भरने पर GREEN underline)
💻 Code Editor (Monaco VS Code Engine)
👀 Live Preview
Address Contact

+91 7877547686

E-mail

onlinecbtportal@gmail.com

Helpline Number

+91 7877547686


Click To Download
Get it on Google Play

ऐप डाउनलोड करने
के लिए Google Play पर
उपलब्ध है

WhatsApp Chat