match / case
match compares one value against several patterns, which is cleaner than a long elif chain:
match command: case "start": print("Go!") case "stop" | "quit": # | means "or" print("Bye") case _: # _ matches anything else print("Unknown")
See it run
shape = "square" match shape: case "circle": sides = 0 case "square" | "rectangle": sides = 4 case _: sides = -1 print(sides)
match compares one value against each case from the top and runs the first that fits.
Practice match / case
Exercise 1
Using day in the editor below and match, set kind to "weekend" when day is "sat" or "sun", and "weekday" otherwise.
Exercise 2
A music player reads command = "pause". Use match to set action: "play" → "Playing", "pause" or "stop" → "Stopped", anything else → "Unknown".
Exercise 3
A desk dispatches request = "renew" and member = False. Use match: "borrow" or "renew" sets reply to "Approved" for members, otherwise "Join first"; "return" always gives "Thank you"; anything else gives "Ask staff".
Free lesson: use the editor to practice it.
Practice
Loading Python…Loading exercise content…
Visualizer Watch your code run line by line
Run your code, then choose Play to follow its execution.
Memory · names → values
Variables appear here as Python creates them.
Output & plots