Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 2.8 — Structural Pattern Matching: match
Python · Example 2 of 2 Python 3.10+

Sequences, mappings and the capture trap

Change point to (7, 0) and command to ["say", "hi", "there"]. Last, read the two final lines: the match on RED succeeded for the wrong reason.

match compares a value against a series of patterns and runs the first case that fits. It can test exact values, alternatives, the shape of lists and dictionaries, and capture parts of what it matched into variables. It is not a C-style switch: a bare name in a case captures, it does not compare.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 6 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Set day = 6. Use match to print Weekend for 6 or 7, Weekday for 1 to 5, and Invalid otherwise.

02

Set point = (3, 0). Use match to print Origin, On the x axis, On the y axis or Elsewhere.

03

Set command = ["add", "milk", "eggs"]. Use a star pattern to print Adding milk and eggs.

04

Set user = {"name": "Asha", "role": "admin", "age": 30}. Use a mapping pattern to print Admin: Asha.

Explain it without notes

01

How is match different from a C-style switch?

02

What does a bare name in a case do, and what is the trap?

03

What does a mapping pattern do with extra keys?

04

When would you choose if/elif or a dictionary over match?

Sequences, mappings and the capture trap Python 3.10+
Sign in to run this example in your browser.

Expected output

on the y axis at 5
move 3 steps north
click at 10 20
matched RED?
RED is now 5