Lesson 57 +10 XP

Match Statements

Match Statements

match is Python's version of a switch statement. It compares a value against several patterns.

Basic match

def http_error(status):
    match status:
        case 400:
            return "Bad request"
        case 404:
            return "Not found"
        case 418:
            return "I'm a teapot"
        case _:
            return "Something else"

The underscore case

case _: is the wildcard. It matches anything and works like else.

Matching with a guard

An if can filter a case:

match point:
    case (0, 0):
        print("Origin")
    case (x, y) if x == y:
        print(f"On the diagonal {x}")
    case (x, y):
        print(f"Point at {x}, {y}")

Matching strings

command = "hello"
match command:
    case "hello":
        print("Hi there!")
    case "bye":
        print("Goodbye!")
    case _:
        print("Hmm?")

Why use match?

It reads cleaner than a long chain of if/elif for many exact comparisons.

TL;DR

  • match value: starts a switch.
  • case pattern: tests one pattern.
  • case _: is the catch-all.
  • Guards with if filter matches further.