Free tools Windows power users keep installed
One-click scans. No signup required.
Some links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.
Python 3.10 and later use match/case for switch-style branching. It is formally called structural pattern matching: it can compare literal values, combine alternatives, and match and unpack data structures. For Python 3.9 and older, use if/elif or a dictionary dispatch instead; those versions cannot parse match syntax. The current Python language reference documents the statement and its behavior.
Write a basic switch-style match
Put the expression to inspect after match, then list patterns in case blocks. This example groups two status codes into one branch and handles every other value with a wildcard:
def describe_status(status):
match status:
case 200:
return "OK"
case 400 | 401:
return "Request or authorization problem"
case 404:
return "Not found"
case _:
return "Other status"
print(describe_status(404)) # Not found
Cases are tested in source order. The first matching case body runs, and the statement then ends: Python does not fall through to subsequent cases. The | pattern means “match either alternative,” and case _: is the catch-all.
Official references: the current language reference and the Python 3.10 tutorial.
#1 Best Overall
Choose between match, if/elif, and a dictionary
| Need | Good fit | Reason |
|---|---|---|
| A few arbitrary conditions, ranges, or compound boolean tests | if/elif |
The conditions are explicit and can express comparisons such as value > 10. |
| Exact alternatives or several literal values sharing a branch, on Python 3.10+ | match/case |
Patterns, OR alternatives, a wildcard, and optional guards are available. |
| Branching on a value’s structure while extracting parts | match/case |
Sequence, mapping, and class patterns can check shape and bind components. |
| Compatibility with Python 3.9 or earlier | if/elif or dictionary dispatch |
The older grammar does not accept match/case. |
| A straightforward key-to-result or key-to-function lookup | Dictionary | Direct dispatch can be compact when no structural matching or complex conditions are needed. |
match is not guaranteed to be faster than alternatives. Python’s specification defines what the statement does, not a speed advantage. Prefer the clearest form, and measure in the actual application if execution time is material. See PEP 634 and PEP 622.
Use patterns, alternatives, and guards correctly
Match literal values
Literal patterns are suitable for fixed choices such as status codes, commands, or event names:
def http_error(status):
match status:
case 400:
return "Bad request"
case 404:
return "Not found"
case 418:
return "I'm a teapot"
case _:
return "Other error"
Literal patterns compare by equality, except None, True, and False, which are matched by identity. That distinction can matter when matching values whose equality behavior is unusual. The rules are specified in PEP 634.
Combine alternatives with |
When several patterns should run the same suite, put them in one OR pattern:
def access_message(status):
match status:
case 401 | 403:
return "Authentication or permission problem"
case _:
return "No access error"
Python uses the first matching case, so keep more specific cases before broader patterns that could also match.
Rank #2
Add a guard for an extra condition
A pattern checks a shape or value; a guard adds a condition that must also be true for the case suite to run:
def describe_value(value):
match value:
case int(number) if number > 0:
return "positive integer"
case _:
return "something else"
Here int(number) matches an integer and binds its value to number; the guard then restricts that branch to positive values. A guard is useful when the condition is more naturally expressed as a boolean test than as a pattern.
Outdated Drivers Are Slowing You Down
One free scan finds every outdated or missing driver and matches the right update for your exact hardware.Free scan · exact hardware matchWindows Errors? Fix Them Before They Spread
Repair common Windows errors and clear accumulated junk for a smoother, more stable PC - no reinstall needed.Free scan · no reinstallMatch structure and extract data
Unlike a basic equality-based switch, match can test whether data has a particular shape and bind pieces of it. For example, splitting a command produces a sequence that can be checked by length and contents:
def handle_command(line):
match line.split():
case ["quit"]:
return "Goodbye"
case ["go", direction]:
return f"Moving {direction}"
case ["get", item]:
return f"Taking {item}"
case _:
return "Unrecognized command"
["go", direction] matches a two-element sequence whose first item is the literal "go"; it binds the second item to direction. A one-element sequence such as ["go"] does not match that case. Structural patterns can also match mappings and class instances. For a structural example and further explanations, see PEP 636.
You can combine a structural check with a guard, for example case [x, y] if x == y:. This matches a two-item sequence only when the two bound items compare equal.
Use the default case—or deliberately omit it
case _: matches anything that has not matched an earlier case. Add it when you need a fallback result, a clear error, or handling for unexpected input. It should generally come after specific patterns so it does not consume every value first.
def label(code):
match code:
case "ok":
return "Success"
case "retry":
return "Try again"
case _:
return "Unknown code"
A wildcard is optional. If no case matches and there is no wildcard, the match statement does nothing and execution proceeds to the next statement after it. That is valid when ignoring unmatched input is intentional; otherwise an explicit fallback makes the behavior easier to see.
Use Python 3.9 or older
Because match/case entered Python in 3.10, code containing that syntax will fail to parse on Python 3.9 and older. If the project must support those versions, use ordinary conditionals or a mapping. An if/elif version handles conditions and ranges naturally:
def describe_status(status):
if status == 200:
return "OK"
elif status in (400, 401):
return "Request or authorization problem"
elif status == 404:
return "Not found"
else:
return "Other status"
For a direct mapping from fixed keys to results, a dictionary can be simpler:
def describe_status(status):
messages = {
200: "OK",
400: "Request or authorization problem",
401: "Request or authorization problem",
404: "Not found",
}
return messages.get(status, "Other status")
Use dictionary dispatch when the relationship is a lookup. Use conditionals when branches rely on ranges or compound tests. Use structural matching when checking input shape and binding its components makes the code clearer.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
Avoid common match/case mistakes
- Do not use a bare name as a constant test.
case RED:is a capture pattern: it binds the subject toREDand matches anything. Use a literal such ascase "red":or a qualified constant such ascase Colors.RED:. - Do not expect fall-through. Only the first successful case suite runs. Put alternatives in the same case with
|if they share behavior. - Do not assume an omitted default raises an error. A nonmatching subject simply continues after the statement; add
case _:if that is not the behavior you want. - Do not treat every match as a basic switch. Sequence, mapping, and class patterns inspect structure and may bind values; the order and meaning of the patterns matter.
- Do not rely on names after a failed partial match. The language reference says not to depend on whether names are set or unchanged after a failed match. Keep later logic independent of such bindings. See the match statement reference.
Troubleshoot syntax and behavior
SyntaxError at match or case
Check the interpreter actually running the file. The syntax requires Python 3.10 or later; upgrading a different Python installation will not help if the command, IDE, or virtual environment still selects an older one. Alternatively, rewrite using if/elif or a dictionary so the code remains compatible.
A case unexpectedly matches every value
Look for a bare name pattern such as case command:. It captures the subject rather than comparing it to a variable named command. For a fixed string use a quoted literal, or use a qualified name for a constant.
A branch never runs
Check the case order and the exact subject shape. An earlier broad pattern may match first; a sequence pattern also checks its length and element positions. Add a temporary print of the subject or test each intended input to confirm what is being matched.
An unmatched input appears to be ignored
That is the defined behavior when no case matches and there is no wildcard. Add a final case _: that returns, logs, or raises as appropriate for the program.
The Tool Desk
Outbyte Driver Updater FREEScan for outdated or missing drivers - takes under a minuteDriver Scan →Outbyte PC Repair FREEClear out junk files and repair common Windows errorsFree Scan →A speed change is uncertain
There is no language-level speed guarantee for match. Benchmark representative inputs in the target application before choosing a branch form for performance reasons; otherwise choose based on clarity.
Best Value
Or skip the browser setup
If your Python task is taking a webpage screenshot rather than choosing a Python branch, ScreenshotNeo offers a one-request screenshot API and an MCP server. Its capture flow removes cookie/consent banners, newsletter popups, and chat widgets before the screenshot; bot checks, blank pages, and failed loads are not billed. AI agents can use its MCP tools for screenshots, page information, and PDF capture.
Install the dependency with python -m pip install requests, then call the API. Keep your access key private and replace the target URL as needed. See the ScreenshotNeo documentation for API options.
import requests
r = requests.get(
"https://api.screenshotneo.com/v1/shot",
params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"},
timeout=90,
)
r.raise_for_status()
open("shot.webp", "wb").write(r.content)
ScreenshotNeo has 1,000 screenshots a month free with no card; paid plans start at $5 for 3,000. Sign up for free screenshots.
Do these 3 things before closing this tab:
1Fix the driver behind crashes, sound loss and screen glitches2Repair Windows errors before they cause bigger problems3Scan for outdated or missing drivers - takes under a minuteFurther reading
- Python language reference: match statement
- The Python 3.10 tutorial: match statements
- PEP 634: Structural Pattern Matching specification
- PEP 636: Structural Pattern Matching tutorial
- PEP 622: Background on pattern-matching semantics and rationale
Frequently Asked Questions
Does Python have switch-case?
Python 3.10 and later have switch-style branching through match/case, a structural pattern matching feature. Older versions use alternatives such as if/elif.
Does match/case fall through in Python?
No. Cases are tried in order, and only the first matching case suite runs.
Quick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

