Dispatch Values with match and case
Core idea
Python 3.10 introduced structural pattern matching. match evaluates a subject expression, then tests case patterns in written order. Only the first successful case runs; control does not fall through. Literal patterns test a specific value. The wildcard _ matches anything and can provide a final fallback. match and case are soft keywords: they have special meaning in these statements, not everywhere.
command = "scan"match command: case "scan": print("reading") case "stop": print("halted") case _: print("unknown")Only the scan branch executes.
Handle unknown commands
command = "pause"match command: case "scan": print("reading") case _: print("unknown")The fallback handles the unmatched value.
Continue without a match
With no successful case and no fallback, execution continues after match.
Common mistake
Use quotes for string literals. Matching is not a switch with fall-through; a break is not needed to end a case.
Practice
Write cases for "open", "close" and unknown commands. Test all three paths.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Dispatch with literal patterns
Check your understanding of match and case.
What is printed?
match "start": case "start": print("go") case _: print("stop")What is printed?
match 3: case 1: print("one")print("done")What is printed?
match "wait": case "scan": print("scan") case _: print("other")What minimum Python version supports match and case?