Dispatch commands with match and case
Select a branch for an exact value and provide a default.
Jump to the automation labA match statement checks the subject against each case in order. Use literal strings for command names and | to combine aliases in one case. A final case _: handles everything else.
Use if and elif for comparisons such as ranges. Match is useful when discrete commands or structured patterns share a common subject.
Clean up spaces and letter case before dispatch.
Run the example and practice
Handle both “list” and “show” by returning “Show items”. Keep the existing commands and fallback.
Target output
Create item
Show items
Unknown commandShow a hint
Add another case before the wildcard and join the aliases with |.
Ready
Run your code to see the output here.
Check output also tests your code with additional cases.
The first run downloads Python. Code runs in your browser. Progress and drafts are stored on this device.
Show one solution
def route(command):
match command.strip().lower():
case "add" | "new":
return "Create item"
case "list" | "show":
return "Show items"
case _:
return "Unknown command"
print(route(" NEW "))
print(route("show"))
print(route("remove"))Automation lab
Map shortcut names to preview actions
Print the action for a named shortcut so you can test the mapping before connecting it to a desktop macro.
Ready
Run the example to see the output here.
Give the previous-slide action two names and test both.
Further reading in Automate the Boring Stuff with Python by Al Sweigart