Hintor
Python Basics for Programmers

Pattern Matching with match and case

Python for Developers/Python Basics for Programmers/

Pattern Matching with match and case

Python

Lesson explanation

Pattern Matching with match and case


🎯 Learning Objective

After this lesson, you will be able to:

  • Route one value through literal case patterns.
  • Add a final fallback with the wildcard _.
  • Combine equivalent patterns with |.
  • Add a guard when a matched pattern needs one extra condition.

Short Explanation

Python's match statement is useful when one value can take several known shapes or commands. It is similar to switch in other languages, but Python calls it structural pattern matching.

Python
match command:
    case "start":
        print("Starting")
    case "stop":
        print("Stopping")
    case _:
        print

Python checks cases from top to bottom and runs the first matching case. There is no fall-through, so you do not add break after each branch.

Use | when several literal values should share one result. A guard adds an if condition after a pattern when matching the value alone is not enough.

For simple thresholds such as score >= 90, regular if / elif / else remains clearer. This lesson focuses on literal routing, alternatives, fallbacks, and one guarded case—not advanced sequence or object patterns.

💡 Tip: Keep the wildcard fallback last. It matches anything that earlier cases did not handle.


Clean Code Examples

1. Route a command

Each literal case handles one known command.

Python
command = "pause"

match command:
    case "start":
        print("Worker: starting")
    case "pause":
        print("Worker: paused")
    case _:

Output:

TEXT
Worker: paused

Only the first matching case runs.

2. Use a wildcard fallback

The wildcard _ handles values that were not listed explicitly.

Python
export_format = "xml"

match export_format:
    case "csv":
        print("Exporter: CSV")
    case "json":
        print("Exporter: JSON")
    case _:

Output:

TEXT
Exporter: unavailable

The wildcard should appear after the specific cases.

3. Combine equivalent values

Use | when several patterns lead to the same branch.

Python
method = "HEAD"

match method:
    case "GET" | "HEAD":
        print("Request: read")
    case "POST" | "PUT":
        print("Request: write"

Output:

TEXT
Request: read

The branch runs when either literal matches.

4. Add a guard

A guard refines a matched case with an additional condition.

Python
event_type = "payment"
amount = 1250

match event_type:
    case "payment" if amount >= 1000:
        print("Payment: manual review")
    case "payment":
  

Output:

TEXT
Payment: manual review

The guarded payment case must come before the broader payment case.


GoalPattern

⚠️ Common Mistakes

  1. Do not add break after each case; Python does not fall through to the next case.
  2. Do not place case _ before specific cases.
  3. Do not use match for ordinary numeric thresholds that are clearer with if / elif.
  4. Do not assume a bare name compares with an existing variable; this lesson uses explicit literals to avoid accidental capture patterns.
Start Practice

Python for Developers

Pattern Matching with match and case

6 tasks
Lesson progress0 / 6 tasks completed

Tasks

Practice progress

Complete the fallback pattern

View task

Complete the final case so every unsupported command reaches the fallback branch.

Requirements

  • Keep the existing commands and messages unchanged.
  • Fill only the missing pattern.

Expected output

Action: unsupported
Code: PythonTask 1

Complete the fallback pattern

Change the starter code or fill in the blanks, then run it before asking Hintor.

1
2
3
4
5
6
7
8
9
10

Assembled code

Preview of the code that will run

Generated code is hidden by default. Expand it only if you want to inspect what your current blank values produce.

Output / ConsolePreparing Python runtime...

0 / 6 tasks completed

Previous lessonBack to unitBack to track
(
"Unknown command"
)
print("Worker: unsupported")
print("Exporter: unavailable")
)
case _:
print("Request: unsupported")
print
(
"Payment: automatic"
)
case _:
print("Event: ignored")
Match one literalcase "start":
Match either literal`case "GET"
Add another conditioncase "payment" if amount > 0:
Handle everything elsecase _: