Skip to content
Justice Tech School

The match Statement

match (Python 3.10 and newer) compares a value with several case patterns, a bit like switch in other languages. The underscore case is the default. A pattern can use | for alternatives and an if guard.

Example
def describe(code):
    match code:
        case 200:
            return "OK"
        case 404:
            return "Not found"
        case 500 | 503:
            return "Server problem"
        case _:
            return "Unknown"

for c in (200, 404, 503, 999):
    print(c, describe(c))

Result

200 OK
404 Not found
503 Server problem
999 Unknown

Exercise

Write the default case.

match x:
    case 1:
        pass
    case :
        pass

Quiz Test

Which pattern is the default in match?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.