Python Module 3 – Control flow: decisions, loops and pattern matching
Pattern matching with match and case
Compare a value with literal, OR and wildcard patterns in a Python match statement, capture values, add guards and avoid the bare-name capture trap.
What you will learn
- Predict which case of a match statement runs for a given subject
- Match a subject against literal, OR and wildcard patterns
- Capture values with names and add guards to cases
- Explain why case NAME captures instead of comparing, and compare with dotted names
- Choose between a match statement and an if and elif chain
Before you start
What you’ll learn · Before you start
What you will learn
- Predict which case of a match statement runs for a given subject
- Match a subject against literal, OR and wildcard patterns
- Capture values with names and add guards to cases
- Explain why case NAME captures instead of comparing, and compare with dotted names
- Choose between a match statement and an if and elif chain
Before you start
On this page
A web server answers each request with a status code such as 200, 404 or 429, and a function that names the code
with if and elif writes the same status into every test of its chain. A match statement takes one value and
checks it against a list of pattern: What a case of a match statement tests its subject against: a literal such as "+", alternatives joined with |, the wildcard _, a name that captures, or a dotted name that compares., one case at a time, until one of them fits. It
can replace a long chain of if and elif tests that all look at the same value, and it can do more than compare: a
pattern can also pull values out into names for the code that follows.
This lesson covers the patterns you will use most: fixed values, alternatives, a catch-all, names that capture the value, and conditions called guards. You can step through two match statements case by case. The next lesson takes patterns further, into lists, dictionaries and objects.
A match runs the first case that fits, and only that one
The value after match is the subject: The value written after match. Python evaluates it once, then tries the patterns of the cases against it, from the top.. Python evaluates it once and then tries the
case lines from top to bottom. The first case whose pattern fits, and whose guard (if it has one) is true, runs its
indented block. Then the whole statement is finished: no other case runs, even if it would have fitted too, and there
is no break to write.
How a match statement chooses a case
Text description of the diagram
The diagram is a flow chart that runs from top to bottom.
- Python evaluates the subject, the expression after match, once.
- It takes the next case, starting with the first one.
- If that case's pattern does not fit the subject, it goes back to step 2 with the case after it.
- If the pattern fits, Python checks the guard, the if part after the pattern. A case without a guard counts as true here. If the guard is false, it goes back to step 2.
- If the guard is true, Python runs that case's block and skips every other case.
- When no case is left to try, the match statement ends without running any block and without raising an error.
Follow one subject through a real match statement, the calculator of the next section, called with the operator "×":
The drawing shows the whole scene; its 6 steps are listed below.
Every step as text
- The subject. calculate(7, "×", 5) reaches the match. Python evaluates the subject, operator, once: it is the string "×".
- A literal that does not fit. The first pattern is the literal "+". "×" == "+" is false, so the pattern does not fit, and Python tries the next case.
- Another literal. "×" is not "-" either, so the second case does not fit. Nothing has run yet.
- An OR pattern fits. The OR pattern fits if any of its alternatives does. "*" and "x" do not, but "×" does, so this case fits.
- Its block runs. The block of this case runs: return a * b gives 35. That ends the whole match statement; there is no break to write.
- The rest is never tried. The last two cases are never tried for "×". The wildcard at the end answers only for a subject that every case above it missed, such as "^".
Python tried three cases and ran one. The two cases below the one that fitted were never tried at all. That is the
difference from the switch statement of C, and of Java with case …: labels, where execution falls through from one
case into the next unless a break stops it.
If no case fits, the statement does nothing at all. Python raises no error, which is convenient and, as you will see, also an easy way to hide a bug.
Key idea
Python evaluates the subject once, tries the cases from the top and runs the block of the first one that fits; then the match statement is over.
Checkpoint
Check: The first case that fits
Literal, OR and wildcard patterns say what a case fits
The simplest pattern is a literal: A value written straight into the code, such as 42, 3.5, 0xFF or "text". How a number literal is written decides its type; a decimal point or an e makes a float. More in “Integers, floats and arithmetic operators”: a number, a string, True, False or None written in
the case line. It fits when the subject equals it. This calculator chooses what to do from the operator the user
typed:
def calculate(a, operator, b):
match operator:
case "+":
return a + b
case "-":
return a - b
case "*" | "x" | "×":
return a * b
case "/" | "÷":
return a / b
case _:
raise ValueError(f"unknown operator: {operator!r}")
print(calculate(7, "+", 5))
print(calculate(7, "×", 5))
print(calculate(7, "/", 2))
try:
print(calculate(7, "^", 2))
except ValueError as error:
print("ValueError:", error) Output
12 35 3.5 ValueError: unknown operator: '^'
Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 calculator.py
Runs on this device, in your browser. The first run downloads Python (about 13.5 MB), which is kept for the next runs.
Your run, in this browser
Three kinds of pattern are at work:
case "+":is a literal pattern. It fits whenoperator == "+".case "*" | "x" | "×":is an OR pattern: the|lists alternatives, and the case fits if any one of them does. People type multiplication in several ways, and one case handles them all.case _:is the wildcard: The pattern _, which fits any subject and binds no name. As the last case of a match it catches every subject the cases above it missed.. The underscore fits any subject, so a lastcase _handles everything the cases above it did not. Here it raises aValueErrorthat names the operator the calculator does not know.
True, False and None are the exception to “equals”: they are compared by identity (is), so case True: does
not fit the number 1, even though 1 == True.
A common mistake: no case for the rest
Leave out the wildcard and an unexpected subject simply falls through the whole statement:
def size_name(code):
match code:
case "S":
return "small"
case "M":
return "medium"
case "L":
return "large"
print(size_name("M"))
print(size_name("XL")) Output
medium None
Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 sizes.py
Runs on this device, in your browser. The first run downloads Python (about 13.5 MB), which is kept for the next runs.
Your run, in this browser
"XL" fits none of the three cases, so the match does nothing, the function reaches its end without a return, and
it returns None. The program carries on with a wrong value and fails later, somewhere else, which makes the bug hard
to trace. Unless doing nothing really is right, end with case _: and return a clear value or raise an exception,
as the calculator does.
Checkpoint
Check: Literal, OR and wildcard patterns
A capture binds the subject, and a guard adds a test
A bare name in a pattern, such as code, is a capture pattern: A bare name in a case, such as case code:, which fits any subject and binds it to that name. It never compares, so case SHIPPED: overwrites a constant instead of testing it.. It fits any subject
and assigns the subject to that name, which the case can then use. On its own that matches everything, so it is
usually combined with a guard: An if condition after a case's pattern, as in case code if code < 200:. Python checks it only once the pattern fits; when it is false, the next case is tried.: if and a condition after the pattern. Python checks the
guard only once the pattern has fitted; if the guard is false, it goes on to the next case.
Every HTTP response carries a three-digit status code, and the HTTP standard sorts them into five classes by their first digit. This function names two common codes exactly and classifies the rest:
def describe(status):
match status:
case 200:
return "200 OK"
case 404:
return "404 Not Found"
case code if 100 <= code <= 199:
return f"{code}: informational"
case code if 200 <= code <= 299:
return f"{code}: successful"
case code if 300 <= code <= 399:
return f"{code}: redirection"
case code if 400 <= code <= 499:
return f"{code}: client error"
case code if 500 <= code <= 599:
return f"{code}: server error"
case _:
return f"{status}: not an HTTP status code"
for status in [200, 204, 301, 404, 429, 503, 99]:
print(describe(status)) Output
200 OK 204: successful 301: redirection 404 Not Found 429: client error 503: server error 99: not an HTTP status code
Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 http_status.py
Runs on this device, in your browser. The first run downloads Python (about 13.5 MB), which is kept for the next runs.
Your run, in this browser
Step through the call describe(429) and watch the captures and the guards, case by case:
The drawing shows the whole scene; its 6 steps are listed below.
Every step as text
- The subject. describe(429) reaches the match, and Python evaluates the subject once: status is 429.
- Two literals. 429 is neither 200 nor 404, so the two literal patterns do not fit.
- A capture, a false guard. case code is a capture pattern: it fits any subject and binds it, so code is now 429. Only then is the guard checked, and 100 <= 429 <= 199 is false, so Python tries the next case.
- Two more false guards. The next two cases capture 429 again. Their guards, 200 to 299 and 300 to 399, are false as well, so neither case runs.
- The guard is true. 400 <= 429 <= 499 is true, so this case runs and returns "429: client error". The match statement is over.
- Never tried. The 5xx case and the wildcard are never tried for 429. A false guard does not stop the match: it only lets the next case try.
Notice the order of the cases. 200 is also in the range of the “successful” guard, but case 200 comes first, so it
wins. Put specific cases above general ones: a broad case placed early would answer for every value it covers, and
the cases below it would never run.
The guards compare numbers, so describe("404"), with the code as text, would raise a TypeError inside the first
guard: a guard that fails with an error stops the whole match. The next lesson shows patterns that check the type
of the subject before any guard runs.
Checkpoint
Check: Captures and guards
The capture trap: a bare name never compares
Because a bare name captures, it cannot be used to compare with a constant, and the mistake is easy to make because
the code reads naturally. The program below means “if the status is the value of SHIPPED”, but that is not what
it says:
SHIPPED = "shipped"
for status in ["packed", "shipped", "cancelled"]:
match status:
case "packed":
print(status, "-> being packed")
case SHIPPED:
print(status, "-> on its way")
print("SHIPPED is now", repr(SHIPPED)) Output
packed -> being packed shipped -> on its way cancelled -> on its way SHIPPED is now 'cancelled'
Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 capture_trap.py
Runs on this device, in your browser. The first run downloads Python (about 13.5 MB), which is kept for the next runs.
Your run, in this browser
case SHIPPED: fits every subject and assigns it to SHIPPED. The cancelled order is reported as on its way, and
because this loop runs at the top level of the file, the constant itself has been overwritten with 'cancelled'.
Python catches one form of this mistake for you. When a capture pattern without a guard is followed by more cases, those cases could never run, and Python refuses to run the file:
SHIPPED = "shipped"
def label(status):
match status:
case SHIPPED:
return "on its way"
case _:
return "something else"
print(label("cancelled")) Output (exit status 1)
Printed as an error (standard error)
File "capture_error.py", line 6
case SHIPPED:
^^^^^^^
SyntaxError: name capture 'SHIPPED' makes remaining patterns unreachable
Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 capture_error.py
Runs on this device, in your browser. The first run downloads Python (about 13.5 MB), which is kept for the next runs.
Your run, in this browser
To compare with a named value, use a dotted name, such as Status.SHIPPED. A name with a dot in it is a
value pattern: A dotted name in a case, such as case Status.SHIPPED:. Python looks the value up and compares the subject with ==, so it tests a constant without capturing.: Python looks the value up and compares the subject with ==. An
enumeration (an Enum class) is a natural home for such names, and a StrEnum’s members are strings, so they compare
equal to text such as "shipped" read from a file or typed by a user:
from enum import StrEnum
class Status(StrEnum):
PACKED = "packed"
SHIPPED = "shipped"
def label(status):
match status:
case Status.PACKED:
return "being packed"
case Status.SHIPPED:
return "on its way"
case _:
return "unknown status"
for status in ["packed", "shipped", "cancelled"]:
print(status, "->", label(status)) Output
packed -> being packed shipped -> on its way cancelled -> unknown status
Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 status_enum.py
Runs on this device, in your browser. The first run downloads Python (about 13.5 MB), which is kept for the next runs.
Your run, in this browser
The rule to remember: literals and dotted names compare; a bare name captures, and the single underscore matches
anything without capturing. If you would rather not write a class, a literal (case "shipped":) works too.
Key idea
A bare name in a case captures and fits everything; to compare with a constant, write a literal or a dotted name
such as Status.SHIPPED.
Checkpoint
Check: The bare-name capture trap
match and case are soft keywords
match and case are keywords only where a match statement can stand. Everywhere else they are ordinary names, so
programs written before Python 3.10 that use a variable called match still run. The keyword module calls them
soft keyword: A word that is a keyword only in one kind of statement, such as match, case or type, and an ordinary name everywhere else. More in “Variables, objects and names in Python”:
import keyword
import re
print("match is a keyword:", keyword.iskeyword("match"))
print("match is a soft keyword:", keyword.issoftkeyword("match"))
print("soft keywords:", keyword.softkwlist)
# Outside a match statement, match is an ordinary name.
match = re.search(r"\d+", "Invoice 381 is paid")
print(match.group()) Output
match is a keyword: False match is a soft keyword: True soft keywords: ['_', 'case', 'match', 'type'] 381
Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 soft_keywords.py
Runs on this device, in your browser. The first run downloads Python (about 13.5 MB), which is kept for the next runs.
Your run, in this browser
The underscore is on the list because it is special inside patterns only, and type because it starts a type alias
statement; outside those places, all four are names you may use.
Version note
The match statement is new in Python 3.10 (PEP 634), so code that uses it needs Python 3.10 or newer; older versions
reject it with a SyntaxError. This track runs Python 3.14. StrEnum is newer still, from Python 3.11. Python 3.15
adds a fifth soft keyword, lazy, which is special only in front of an import statement.
Checkpoint
Check: Soft keywords
Use match for one subject, and if and elif for mixed tests
Both choose between blocks of code, and many choices can be written either way. Reach for match when several cases
look at the same subject: each case then reads as one line, “this value” or “one of these values”, and the patterns
of the next lesson can take the subject apart while they test it. Keep if and elif for two or three tests, and for
conditions that involve different values, such as if age < 18 and not signed_by_parent:. The two share one habit
worth keeping: when nothing fits, nothing runs, so end a match with case _ and an if chain with else whenever
every value needs an answer.
| The choice | match |
if and elif |
|---|---|---|
| Many cases test one value | One line a case | status == repeated in every test |
| Tests on different values | Needs guards for each | Natural: any condition per test |
| Two or three tests | Possible, but longer | Shorter |
| Nothing fits | case _ catches the rest |
else catches the rest |
| Taking the value apart | Patterns do it (next lesson) | Indexing and extra tests |
A rule of thumb
When every test of a chain starts with the same name and ==, write a match; when the tests mix names and
conditions, keep the if chain.
Checkpoint
Check: match or an if chain
Practise: answer a music player’s commands
The exercise asks for a match statement with OR patterns, a capture with a guard for the volume and a wildcard for
everything else. Its sample tests try every command, spellings with capital letters and spaces around them, and
volumes on both sides of the limits.
Exercise · Easy · Python
Answer a music player's commands with match
A music player has a text box for commands. Write respond(command), which returns the player's reply to one command, using a match statement (the tests check that there is one).
First remove the spaces at both ends of the command and make it lower case, so that " Play " counts as "play". Then reply:
- to
play:Playing - to
pauseorstop:Paused - to
nextorskip:Next song - to
helpor?:Commands: play, pause, next, help, or a volume from 0 to 100 - to a whole number from 0 to 100, such as
35:Volume 35 - to anything else:
Unknown command: 'dance', with the cleaned command in quotes asrepr()writes it
So respond("SKIP") returns "Next song", respond("101") returns "Unknown command: '101'" and respond("") returns "Unknown command: ''".
Starter code · player.py
def respond(command):
"""Return the music player's reply to one typed command."""
text = command.strip().lower()
match text:
case "play":
return "Playing"
case _:
return f"Unknown command: {text!r}" The sample tests · test_player.py
import ast
from pathlib import Path
from player import respond
HELP = "Commands: play, pause, next, help, or a volume from 0 to 100"
def test_play():
"""replies Playing to play"""
assert respond("play") == "Playing"
def test_pause_and_stop():
"""treats pause and stop the same"""
assert respond("pause") == "Paused"
assert respond("stop") == "Paused"
def test_next_and_skip():
"""treats next and skip the same"""
assert respond("next") == "Next song"
assert respond("skip") == "Next song"
def test_help():
"""lists the commands for help and ?"""
assert respond("help") == HELP
assert respond("?") == HELP
def test_spaces_and_case():
"""ignores spaces at both ends and upper case letters"""
assert respond(" Play ") == "Playing"
assert respond("SKIP") == "Next song"
def test_volume():
"""sets the volume for a whole number from 0 to 100"""
assert respond("35") == "Volume 35"
assert respond("0") == "Volume 0"
assert respond("100") == "Volume 100"
def test_volume_out_of_range():
"""does not set a volume above 100 or below 0"""
assert respond("101") == "Unknown command: '101'"
assert respond("-5") == "Unknown command: '-5'"
def test_unknown():
"""names a command it does not know"""
assert respond("dance") == "Unknown command: 'dance'"
assert respond("") == "Unknown command: ''"
assert respond(" Dance ") == "Unknown command: 'dance'"
def test_uses_match():
"""uses a match statement"""
source = Path(__file__).with_name("player.py").read_text(encoding="utf-8")
assert any(isinstance(node, ast.Match) for node in ast.walk(ast.parse(source))) A hint
Put the cleaned text in a variable and match on it: text = command.strip().lower(). A command with two spellings is one OR pattern, such as case "pause" | "stop":. For the volume, capture the text with a name and add a guard: "35".isdecimal() is True and "-5".isdecimal() is False, so check the text before you call int() on it.
Results of the sample tests
| Test | Result | Details |
|---|
What your code printed
The sample tests run on this device, in your browser (Pyodide): nothing is sent to mysmartcopilot.com. The first run downloads Python (about 13.5 MB), which is kept for the next runs. A check in your browser is feedback for you, not proof that the code is right for every input.
Finish with the practice questions. They adapt to your answers, start with the idea you are least sure of, and say for every choice what makes it right or wrong:
Practice that adapts to you
Practise this lesson
15 questions about 6 ideas of this lesson. Each answer is explained at once, and what you get right is kept in this browser.
Interview questions
Fresher · How does Python’s match statement differ from a switch statement in C or Java?
A classic switch compares one value with constants. In C, and in Java with case …: labels, execution falls
through from one case into the next unless a break stops it. Python’s match never falls through: it tries its
cases from the top, runs the block of the first one whose pattern fits and whose guard is true, and then the statement
is over, with no break to write. If no case fits, nothing runs and no error is raised, so a final case _ matters.
The patterns do more than compare: | lists alternatives, a bare name captures the subject, a guard adds any
condition, and the patterns of the next lesson take lists, dictionaries and objects apart. The trap is that a bare
name never compares, so a constant is written as a literal or a dotted name such as Status.SHIPPED. It needs Python
3.10 or newer.
Model answers open with any pass: ₹79 for 1 week ($2.99), one payment that never renews.
-
Fresher to mid
A teammate writes case MAX_RETRIES: as the last case of a match on an attempt counter, meaning to compare it with the module constant MAX_RETRIES = 3. The tests pass. What does the case really do, why can the tests still pass, and how do you fix it so the mistake cannot come back?
-
Mid to senior
A chat bot answers 25 typed commands with one match statement, and a new command is added every week. A teammate wants to replace the match with a dictionary that maps each command to a function. When is that the better design, when is match better, and what would you change first?
Key takeaways
matchevaluates the subject once and runs the first case whose pattern fits and whose guard is true; there is no fall-through and nobreak.- Literal patterns compare with
==(True,FalseandNonewithis),|gives alternatives, andcase _catches everything else. - When no case fits, nothing happens and no error is raised, so end with
case _unless doing nothing is right. - A bare name captures the subject; a guard (
case code if code < 200:) adds a condition that is checked after the pattern fits. - To compare with a constant, use a dotted name such as
Status.SHIPPEDor a literal, never a bare name. - Use
matchwhen many cases test one subject, and anifchain when the tests mix values and conditions.
Terms in this lesson
- capture pattern
- A bare name in a case, such as case code:, which fits any subject and binds it to that name. It never compares, so case SHIPPED: overwrites a constant instead of testing it.
- guard
- An if condition after a case's pattern, as in case code if code < 200:. Python checks it only once the pattern fits; when it is false, the next case is tried.
- pattern
- What a case of a match statement tests its subject against: a literal such as "+", alternatives joined with |, the wildcard _, a name that captures, or a dotted name that compares.
- subject
- The value written after match. Python evaluates it once, then tries the patterns of the cases against it, from the top.
- value pattern
- A dotted name in a case, such as case Status.SHIPPED:. Python looks the value up and compares the subject with ==, so it tests a constant without capturing.
- wildcard
- The pattern _, which fits any subject and binds no name. As the last case of a match it catches every subject the cases above it missed.
References
- The Python Tutorial: match statements (Python Software Foundation)
- The Python Language Reference: the match statement (Python Software Foundation)
- PEP 634: Structural Pattern Matching: Specification (Python Software Foundation)
- PEP 635: Structural Pattern Matching: Motivation and Rationale (Python Software Foundation)
- PEP 636: Structural Pattern Matching: Tutorial (Python Software Foundation)
- What's New In Python 3.10: structural pattern matching (Python Software Foundation)
- enum: StrEnum (Python Software Foundation)
- keyword, testing for Python keywords (Python Software Foundation)
- Lexical analysis: soft keywords (Python Software Foundation)
- The Java Language Specification, Java SE 21: 14.11.3 Execution of a switch Statement (Oracle)
- RFC 9110: HTTP Semantics, section 15 (status codes) (Internet Engineering Task Force (IETF))
Related tools
Report a problem with this lesson
Kept only in this browser. Your Learn progress