Hackforge Academy

Category: python

Introduction to match-case

Published on 27 Oct 2026

Explanation

Structural pattern matching was introduced in Python 3.10. It selects the first matching case and can match values or structures.

Code:

def describe(status):
    match status:
        case 200: return 'OK'
        case 404: return 'Not Found'
        case _: return 'Unknown'
print(describe(200))

Explanation

Literal patterns match specific strings, while _ is a wildcard that matches any remaining value.

Code:

def action(command):
    match command:
        case 'start': return 'Starting'
        case 'stop': return 'Stopping'
        case _: return 'Invalid command'
print(action('start'))

Explanation

Sequence patterns can match a particular structure; a starred name captures remaining elements.

Code:

def process(data):
    match data:
        case [x, y]: return f'Two: {x}, {y}'
        case [first, *rest]: return f'First: {first}, rest: {rest}'
        case _: return 'Unsupported'
print(process([1, 2, 3]))

Explanation

Mapping patterns match required keys and allow extra keys in the dictionary.

Code:

def handle(event):
    match event:
        case {'type': 'user_created', 'name': name}: return f'Created {name}'
        case {'type': 'user_deleted', 'user_id': uid}: return f'Deleted {uid}'
        case _: return 'Unknown'
print(handle({'type': 'user_created', 'name': 'Arun'}))

Explanation

A guard adds an if condition to a case. Both the pattern and guard must match for that case to run.

Code:

def classify(value):
    match value:
        case int() as n if n < 0: return 'Negative'
        case int() as n if n == 0: return 'Zero'
        case int() as n if n > 0: return 'Positive'
        case _: return 'Not an integer'
print(classify(-5), classify(0), classify(2.5))

πŸš€ Learn Spring Boot with real-world projects

πŸ’‘ Build REST APIs step by step

🧠 Improve backend development skills

🎯 Get career-ready practical training

Join Our Free WhatsApp Community

Direct access to niche-specific mentors and peers on WhatsApp.

🐍

Python Community

Discuss Django, FastAPI, AI integration, and automation scripts with 15k+ developers.

Join Python Community
βš›οΈ

React Community

Master Next.js, Framer Motion, and State Management. Share your latest UI components.

Join React Community
β˜•

Java Community

Deep dives into Spring Boot, Microservices architecture, and high-performance backend ops.

Join Java Community