🐍 Match / Case
Good to know
⭐️ Python has no traditional switch-case, but since Python 3.10 you can use match / case, which is more powerful and expressive. It supports simple matching, multiple options, default cases, and even pattern matching.
Basic Match/Case
Works like a classic switch-case.
command = "start"
match command:
case "start":
print("Engine started")
case "stop":
print("Engine stopped")
case _:
print("Unknown command") # default caseMultiple Options in One Case
Use | to match several values.
status = 404
match status:
case 200 | 201:
print("Success")
case 400 | 404:
print("Client error")
case _:
print("Other status")Match With Variables (Binding)
You can capture parts of the pattern.
message = ("error", 500)
match message:
case ("error", code):
print("Error code:", code)
case _:
print("Unknown message")Match Structured Data (Tuples, Lists, Dict-like)
Pattern matching can inspect structure.
data = ["move", 10]
match data:
case ["move", steps]:
print("Move", steps, "steps")
case _:
print("Invalid command")Match Against Types
Useful for safely handling mixed inputs.
value = 3.14
match value:
case int():
print("Integer")
case float():
print("Float")
case str():
print("String")Match with Guards (If-Conditions)
Add extra logic to a case.
number = 12
match number:
case x if x % 2 == 0:
print("Even number")
case _:
print("Odd number")