Pattern Matching (match/case)

say it: “MACH KAYS” /ˈmætʃ ˈkeɪs/ or “PAT-ern MACH-ing” /ˈpætərn ˈmætʃɪŋ/

match/case: compares a value against patterns and runs the first that fits.

What is pattern matching (match/case)?

Pattern matching compares a value against several patterns with match and case and runs the first one that fits. It reads more cleanly than a long if/elif chain.

command = "stop"
match command:
    case "start":
        print("Starting")
    case "stop":
        print("Stopping")      # this one runs
    case _:
        print("Unknown command")

Level: Journeyman · More Python terms at this level

Updated