Match
Suppose we have a variable, either a simple one like an Int
or a more complex tuple or list, and want to test its contents. A Python match statement can help with this requirement.
While an if
-statement could work instead of match, the match syntax is more elegant and can make programs more maintainable. Match
usually results in shorter code.
This program has several possible match statements, each with various case statements. It is meant to demonstrate many possible ways of using match.
# Part 1: use simple match statement with default case. value = 10 match value: case 5: print("Five matched!") case 7: print("Seven matched!") case _: print("Default case") # Part 2: use if statement inside case statement. done = True match value: case 10 if done: print("Done, case 10 matched") case _: print("Not reached") # Part 3: capture a variable as part of a case statement inside a match. animal = ("bird", 10) match animal: case ("cat", weight): print("Cat weight is", weight) case ("bird", weight): print("Bird weight is", weight) # Part 4: use multiple cases in a single statement. code = 10 match code: case 5 | 10 | 15: print("Multiple of 5") case _: print("Not reached") # Part 5: match a list. items = ["bird", "frog", "dog"] match items: case []: print("Empty") case ["bird", "frog", x]: print("Matched bird, frog and", x)Default case Done, case 10 matched Bird weight is 10 Multiple of 5 Matched bird, frog and dog
It is possible to replace if
-statements with equivalent match-statements in Python, and this can sometimes simplify the syntax of programs.