Home
Python
match Statement Examples
This page was last reviewed on Apr 26, 2024.
Dot Net Perls
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.
if
Example. 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 We have a variable with value 10, and it does not match the cases 5 or 7, so it is matched by the default case (with the underscore).
Part 2 We can use a guard clause (an if statement as part of a case) to only reach a case if the expression evaluates to true.
Part 3 Sometimes we have a complex variable (like a tuple) and only want to match part of it. We can capture the unmatched part as a variable.
Tuple
Part 4 We can handle multiple cases in a single case statement by chaining them together with a vertical bar (an or-operator).
Part 5 Other complex variables, like lists, can be matched in the cases of a match statement.
List
# 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
Summary. It is possible to replace if-statements with equivalent match-statements in Python, and this can sometimes simplify the syntax of programs.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Apr 26, 2024 (new).
Home
Changes
© 2007-2024 Sam Allen.