Codzy

match and case

match compares a value against several possible cases, a bit like a chain of if / elif, but more readable. Each case gives a value to test; the first one that matches runs.

You can group several values with | ("or"): case 404 | 410:. The case _: catches everything that didn't match any other case, like an else. match has existed since 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")

Start the lesson