match looks like a nicer elif chain, but it is better at taking a list apart by shape. It needs Python 3.10 or newer.
def handle(cmd):
match cmd.split():
case ["go", direction]:
return f"going {direction}"
case ["take", *items] if items:
return f"taking {', '.join(items)}"
case ["quit" | "exit"]:
return "bye"
case _:
return "huh?"
for c in ["go north", "take lamp key", "exit", "dance", "take"]:
print(c, "->", handle(c))
Output:
go north -> going north
take lamp key -> taking lamp, key
exit -> bye
dance -> huh?
take -> huh?
A pattern binds names (direction, items), *items grabs the rest, | offers alternatives, and if adds a guard. A bare take fell through to _ because the guard needs at least one item.
The caveat: a bare name in a pattern is a capture, not a comparison. If you write case RED: with a constant called RED, it matches anything. Python catches the worst case, since a later case _ then fails with SyntaxError: name capture 'RED' makes remaining patterns unreachable. Use a dotted name such as Color.RED to compare against a constant.
Further reading: The match statement, PEP 636 – Structural Pattern Matching: Tutorial