Your country

Tools that support it use your country for local currency, number formats, units and paper size. Your choice is saved only in this browser.

Type a name or a two-letter code. Use the up and down arrow keys to move through the countries, Enter to choose one and Escape to close.

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.

  • Beginner
  • 15 minutes
  • Examples run with Python 3.14.8 and Pyodide 314.0.7
  • By MySmartCoPilot
Free lesson, Pro answers: 15 minutes
Free: the whole lesson. With a pass: the model answers to its 2 interview questions.

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.

A match statement evaluates its subject once, then tries each case from the top and runs the first whose pattern fits and guard is true.match subject:evaluated onceTake the next case,from the topPatternfits?Guard true,or no guard?Run its block,skip all othersNo case left:nothing runsyesnoyesnonone left

How a match statement chooses a case

Text description of the diagram

The diagram is a flow chart that runs from top to bottom.

  1. Python evaluates the subject, the expression after match, once.
  2. It takes the next case, starting with the first one.
  3. If that case's pattern does not fit the subject, it goes back to step 2 with the case after it.
  4. 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.
  5. If the guard is true, Python runs that case's block and skips every other case.
  6. 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 "×":

Interactive · stage by stage The subject "×" through the calculator's cases Step through the cases in the order Python tries them. Each box says whether its pattern fits the subject.
The subject "×" through the calculator's cases, step 6 of 6. Showing match operator:, case "+": (does not fit), case "-": (does not fit), case "*" | "x" | "×": (runs: return 7 * 5), case "/" | "÷": (never tried), case _: (never tried). In focus: case "/" | "÷":, case _:.match operator:the subject is '×'case "+":does not fitcase "-":does not fitcase "*" | "x" | "×":runs: return 7 * 5case "/" | "÷":never triedcase _:never tried

The drawing shows the whole scene; its 6 steps are listed below.

Every step as text
  1. The subject. calculate(7, "×", 5) reaches the match. Python evaluates the subject, operator, once: it is the string "×".
  2. 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.
  3. Another literal. "×" is not "-" either, so the second case does not fit. Nothing has run yet.
  4. An OR pattern fits. The OR pattern fits if any of its alternatives does. "*" and "x" do not, but "×" does, so this case fits.
  5. 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.
  6. 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

  1. Question 1 of 2 The calculator is called as calculate(9, "-", 4). How many cases does Python try before it runs one?

    Type a number.

    A hint

    Count from the top, and stop at the first case that fits.

    Show the answer: Question 1 of 2

    Answer: 2 cases

    Python tries case "+", which does not fit, and then case "-", which does, and runs its block. The cases below it are never tried, so two cases are tried in all.

  2. Question 2 of 2 A match statement has no case _, and no case fits its subject. What happens?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: Nothing runs, and no error is raised

    A match statement with no fitting case does nothing at all. End with case _ and return a clear value or raise an exception when every subject needs an answer.

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:

A calculator that matches the operator Python · calculator.py
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

Three kinds of pattern are at work:

  • case "+": is a literal pattern. It fits when operator == "+".
  • 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 last case _ handles everything the cases above it did not. Here it raises a ValueError that 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:

A match with no case for the rest Python · sizes.py
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

"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

  1. Question 1 of 2 Which case of the calculator runs for calculate(6, "x", 2), and what does it return?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: case "*" | "x" | "×", which returns 12

    An OR pattern fits when any of its alternatives fits. People type multiplication as *, x or ×, and the one case handles all three.

  2. Question 2 of 2 What does this print?

    Read the code, then choose one answer.

    match 1:
        case True:
            print("true")
        case _:
            print("other")
    Show the answer: Question 2 of 2

    Answer: other

    Literal patterns compare with ==, except True, False and None, which compare with is. So case True: does not fit the number 1, and the subject falls through to case _.

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:

HTTP status codes with captures and guards Python · http_status.py
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

Step through the call describe(429) and watch the captures and the guards, case by case:

Interactive · stage by stage describe(429), case by case Step through the cases in order. A capture fits any subject; its guard then decides whether the case runs.
describe(429), case by case, step 6 of 6. Showing match status:, case 200: (does not fit), case 404: (does not fit), case code (fits, guard false), case code (fits, guard false), case code (fits, guard false), case code (runs: 429 client error), case code (never tried), case _: (never tried). In focus: case code, case _:.match status:the subject is 429case 200:does not fitcase 404:does not fitcase codefits, guard falsecase codefits, guard falsecase codefits, guard falsecase coderuns: 429 client errorcase codenever triedcase _:never tried

The drawing shows the whole scene; its 6 steps are listed below.

Every step as text
  1. The subject. describe(429) reaches the match, and Python evaluates the subject once: status is 429.
  2. Two literals. 429 is neither 200 nor 404, so the two literal patterns do not fit.
  3. 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.
  4. 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.
  5. The guard is true. 400 <= 429 <= 499 is true, so this case runs and returns "429: client error". The match statement is over.
  6. 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.

HTTP Status Codes Reference Look up what each HTTP status code means and when servers send it.

Checkpoint

Check: Captures and guards

  1. Question 1 of 2 In describe(429), the pattern code of the first guarded case fits, but its guard is false. What does Python do next?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: It tries the next case

    Python checks a guard only after the pattern has fitted, and when the guard is false it moves on to the next case. For 429 that happens three times before the 4xx guard is true.

  2. Question 2 of 2 In http_status.py, case 200: is moved below the case with the guard 200 <= code <= 299. What does describe(200) return now?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: "200: successful"

    Cases are tried from the top, so a broad case placed early answers for every value it covers. Put specific cases, such as case 200, above general ones.

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:

A constant used as a pattern Python · capture_trap.py
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

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:

Python stops the trap when cases follow it Python · capture_error.py
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

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:

Comparing with named constants Python · status_enum.py
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

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

  1. Question 1 of 2 What is the value of SHIPPED once the loop of capture_trap.py has finished?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: 'cancelled'

    case SHIPPED: is a capture pattern. It fits any subject and assigns it to the name SHIPPED, so after the loop the constant holds the last status that reached it, 'cancelled'.

  2. Question 2 of 2 Which case compares the subject with a named constant instead of capturing it?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: case Status.SHIPPED:

    Literals and dotted names compare; bare names capture. Put constants in a class, such as an Enum, or write the literal itself.

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”:

match is also an ordinary name Python · soft_keywords.py
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

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

  1. One question Is match = re.search(r"\d+", text) valid in Python 3.14?

    Choose one answer.

    Show the answer: One question

    Answer: Yes; match is a keyword only where a match statement can stand

    match, case, _ and type are soft keywords: special in their own statements, ordinary names elsewhere. The lesson's soft_keywords.py uses match as a variable after asking the keyword module.

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

  1. One question Which of these decisions reads best as a match statement?

    Choose one answer.

    Show the answer: One question

    Answer: A typed command: "start", "stop", "pause" or "help", each with its own reply

    match shines when many cases look at the same subject. When the tests mix values and conditions, or when there are only two cases, an if statement stays clearer.

Python Online Compiler Copy the calculator into the compiler and add a case for the power operator, **.

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 pause or stop: Paused
  • to next or skip: Next song
  • to help or ?: 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 as repr() 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.

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.

  1. Question 1 of 15 Which of these statements about Python's match statement are true?

    Choose every answer that is right.

    Show the answer: Question 1 of 15

    Answer:

    • Only the block of the first case that matches runs
    • When no case matches and there is no case _, nothing runs and no error is raised

    Python tries the cases in order and runs one block at most; there is no fall-through, so no break is needed. If nothing matches, the statement simply ends. The wildcard _ matches anything but binds no name.

  2. Question 2 of 15 What does this print?

    Read the code, then choose one answer.

    match "b":
        case "a" | "b":
            print("first")
        case "b":
            print("second")
    Show the answer: Question 2 of 15

    Answer: first

    A match runs only the first case that fits. A later case that would also fit is never reached, so put the more specific case first when that is the one you want.

  3. Question 3 of 15 What does the | mean in case "y" | "yes":?

    Choose one answer.

    Show the answer: Question 3 of 15

    Answer: The case fits if either alternative fits

    An OR pattern, written with |, fits when any one of its alternatives fits. Here "y" and "yes" share one block.

  4. Question 4 of 15 What does size_name("XL") return in sizes.py?

    Choose one answer.

    Show the answer: Question 4 of 15

    Answer: None

    With no case _, a subject that fits no case runs no block. The function then returns None, and the program carries on with a wrong value until something fails later.

  5. Question 5 of 15 In case code if 400 <= code <= 499:, when does Python evaluate the guard?

    Choose one answer.

    Show the answer: Question 5 of 15

    Answer: After the pattern has matched and the subject has been bound to code

    A guard is checked only for a case whose pattern has already matched, so the names the pattern captured can be used in it. If the guard is false, Python tries the next case.

  6. Question 6 of 15 What does this print?

    Read the code, then choose one answer.

    match 7:
        case 1 | 2 | 3:
            print("small")
        case n if n % 2 == 0:
            print("even", n)
        case n:
            print("odd", n)
    Show the answer: Question 6 of 15

    Answer: odd 7

    7 is not 1, 2 or 3, so the OR pattern fails. The second case captures 7 in n, but its guard n % 2 == 0 is false, so Python moves on. The last case is a capture pattern with no guard, which matches anything.

  7. Question 7 of 15 describe("404") is called with the code as text. What happens?

    Choose one answer.

    Show the answer: Question 7 of 15

    Answer: The first guard raises TypeError, and the match stops there

    A guard that raises an error stops the whole match. The patterns of the next lesson can check the type of the subject first, as in case int(code) if …, so text never reaches a numeric guard.

  8. Question 8 of 15 A file defines SHIPPED = "shipped" and class Status(StrEnum) with the member SHIPPED = "shipped". Which case runs only when the subject equals "shipped"?

    Choose one answer.

    Show the answer: Question 8 of 15

    Answer: case Status.SHIPPED:

    A dotted name is a value pattern: Python looks it up and compares it with ==. A bare name such as SHIPPED or status is a capture pattern and matches anything, and _ is the wildcard, which also matches anything.

  9. Question 9 of 15 What does capture_trap.py print?

    What does this program print? Choose one answer.

    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))
    Show the answer: Question 9 of 15

    Answer: it prints

    packed -> being packed
    shipped -> on its way
    cancelled -> on its way
    SHIPPED is now 'cancelled'

    case SHIPPED: is a capture pattern: it matches any subject and assigns it to the name SHIPPED. So "cancelled" is reported as on its way, and because the loop runs at the top level of the file, the constant itself now holds the last status, 'cancelled'.

  10. Question 10 of 15 Why does Python refuse to run capture_error.py?

    Choose one answer.

    Show the answer: Question 10 of 15

    Answer: A capture without a guard fits everything, so the case after it could never run

    A bare name with no guard matches every subject, so every case below it is unreachable. Python reports that as a SyntaxError before running anything, which catches one form of the capture trap.

  11. Question 11 of 15 In status_enum.py, why does the text "shipped", read as an ordinary string, fit case Status.SHIPPED:?

    Choose one answer.

    Show the answer: Question 11 of 15

    Answer: A StrEnum member is a string, so "shipped" == Status.SHIPPED is True

    Status.SHIPPED is a value pattern, compared with ==. Because StrEnum members are str objects, the member equals the text "shipped", so data read from a file or typed by a user fits the case.

  12. Question 12 of 15 Which of these words is a soft keyword in Python 3.14?

    Choose one answer.

    Show the answer: Question 12 of 15

    Answer: case

    In Python 3.14, keyword.softkwlist lists _, case, match and type (3.15 adds lazy). They are special only in their own statements, so programs that use them as names keep working.

  13. Question 13 of 15 What does this print?

    Read the code, then choose one answer.

    import keyword
    print(keyword.iskeyword("match"), keyword.issoftkeyword("match"))
    Show the answer: Question 13 of 15

    Answer: False True

    keyword.iskeyword() checks the full keywords and keyword.issoftkeyword() the soft ones. match is soft, so it can still name a variable outside a match statement.

  14. Question 14 of 15 What does the job of an if chain's else in a match statement?

    Choose one answer.

    Show the answer: Question 14 of 15

    Answer: case _

    End a match with case _ for the same reason you end an if chain with else: when nothing fits, nothing runs.

  15. Question 15 of 15 Which decision is clearer as an if and elif chain than as a match statement?

    Choose one answer.

    Show the answer: Question 15 of 15

    Answer: No delivery fee when the total is above 500, a smaller fee for members below that, the full fee otherwise

    Choose match when the cases test one subject, and if and elif when the conditions mix values or need more than equality, such as a range of one value combined with another value.

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.

  1. 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?

    Model answer, Pro. Model answers open with any pass; prices are in the notice on this page. First step and follow-ups

  2. 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?

    Model answer, Pro. First step and follow-ups

Key takeaways

  • match evaluates the subject once and runs the first case whose pattern fits and whose guard is true; there is no fall-through and no break.
  • Literal patterns compare with == (True, False and None with is), | gives alternatives, and case _ 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.SHIPPED or a literal, never a bare name.
  • Use match when many cases test one subject, and an if chain 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

Related tools

Report a problem with this lesson

Quick answers and tool search

Type to search tools or to get a quick answer, for example 18% of 2500. Use the up and down arrow keys to move through the results, Enter to choose, and Escape to close.