Learning Sections show
Match-Case Statements
In Python 3.10 and later, the match-case
statement was introduced as a way to perform pattern matching, similar to switch-case statements in other programming languages. It allows you to check the value of a variable against multiple patterns and execute corresponding blocks of code.
Basic Match-Case Statement
The match
statement is followed by an expression and several case
clauses. Each case
specifies a pattern and an action to be taken if the pattern matches the value of the expression.
# Basic match-case statement example
command = "start"
match command:
case "start":
print("Starting...")
case "stop":
print("Stopping...")
case "pause":
print("Pausing...")
case _:
print("Unknown command")
Matching Multiple Patterns
Using the pipe symbol |
, you can match multiple patterns in a single case clause.
# Matching multiple patterns example
status = "open"
match status:
case "open" | "opened":
print("The status is open.")
case "closed" | "shut":
print("The status is closed.")
case _:
print("Unknown status")
Using Guards in Case Clauses
Guards allow you to add additional conditions to a case clause using the if
keyword.
# Using guards in case clauses example
number = 42
match number:
case x if x >> 0:
print("The number is positive")
case x if x == 0:
print("The number is zero")
case x if x < 0:
print("The number is negative")
Pattern Matching with Data Structures
The match-case
statement can also be used to match patterns in data structures like lists and tuples.
# Pattern matching with lists example
data = [1, 2, 3]
match data:
case [1, 2, 3]:
print("Matched [1, 2, 3]")
case [4, 5, 6]:
print("Matched [4, 5, 6]")
case _:
print("No match")
# Pattern matching with tuples example
point = (4, 5)
match point:
case (0, 0):
print("The point is at the origin")
case (x, y):
print(f"The point is at ({x}, {y})")