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
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!
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)
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.
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.
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}")
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`**.
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)
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.
# 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!")
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:
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")
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
elifoperators. - 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
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.
match-case block). Outside pattern matching blocks, match and case remain valid variable identifiers, ensuring existing legacy Python code bases do not break.
_ 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.
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.
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-casesequence 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:
- Header & Setup (Lessons 1-4): Write clear comments and docstrings. Format clean line output banner using custom
sepandendparameters inprint(). Follow PEP 8 variable naming standards. - Variable Assignment & Data Types (Lessons 5-6): Declare product catalog items using string literals, floating-point prices, integers, and Booleans. Store store status variables.
- 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 (
*,+) andround()ormath.ceil(). - String Processing (Lesson 8): Prompt for customer full name and email string. Use
.strip(),.title(), and.split("@")to parse email username and domain accurately. - 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). - 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"). - Conditional Control Flow (Lesson 11): Determine customer discount tier (Gold: 20%, Silver: 10%, Bronze: 5%) using an
if-elif-elseladder. - Pattern Matching (Lesson 12): Use a
match-caseblock 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)
OnlineCBT