match e case
match confronta un valore con diversi casi possibili, un po' come una serie di if / elif, ma più leggibile. Ogni case indica un valore da verificare; viene eseguito il primo che corrisponde.
Si possono raggruppare più valori con | («oppure»): case 404 | 410:. Il caso case _: cattura tutto ciò che non corrisponde a nessun altro caso, come un else. match esiste da Python 3.10.
command = "stop"
match command:
case "start":
print("Starting...")
case "stop":
print("Stopping...")
case _:
print("Unknown command")
code = 404
match code:
case 200:
print("OK")
case 404 | 410:
print("Not found")