Python match...case Statement
match...case provides a more powerful pattern matching approach.
Pattern matching is a way of handling data structures in programming that makes code more concise and readable.
match...case is new syntax introduced in Python 3.10.
The match...case syntax structure is as follows:
match expression:
case pattern1:
# Logic for processing pattern1
case pattern2 if condition:
# Logic to process pattern2 and satisfy the condition
case _:
# Logic for handling other cases
Parameter Description:
matchstatement followed by an expression, then usecasestatements to define different patterns.casefollowed by a pattern, which can be a specific value, a variable, a wildcard, etc.- You can use the
ifkeyword adds a condition incase. _is usually used as a wildcard to match any value.

Example
1. Simple Value Matching
Example
def
match_example
(
value
)
:
match value:
case
1
:
(
"Matched value 1"
)
case
2
:
(
"Matched value 2"
)
case _:
(
"Matched other value"
)
match_example
(
1
)
Output: Matched value 1
match_example
(
2
)
Output: Matched value 2
match_example
(
3
)
Output: Matched other value
In the code above, the match statement is used to match different cases of value; each case statement represents a possible match, and the _ wildcard represents other cases.
The output is:
匹配到值为1
匹配到值为2
匹配到其他值
2. Using Variables
Example
def match_example
(
item
)
:
match item
:
case
(
x
,
y
)
if
x
==
y
:
(
f
"Matched equal tuple: {item}"
)
case
(
x
,
y
)
:
(
f
"Matched tuple: {item}"
)
case
_
:
(
"Matched other cases"
)
match_example
(
(
1
,
1
)
)
Output
:
Matched equal tuple
:
(
1
,
1
)
match_example
(
(
1
,
2
)
)
Output
:
Matched tuple
:
(
1
,
2
)
match_example
(
"other"
)
Output
:
Matched other cases
The output is:
匹配到相等的元组: (1, 1)
匹配到元组: (1, 2)
匹配到其他情况
3. Type Matching
Example
class
Circle:
def
init
(
self
,
radius
)
:
self
.
radius
=
radius
class
Rectangle:
def
init
(
self
,
width
,
height
)
:
self
.
width
=
width
self
.
height
=
height
def
match_shape
(
shape
)
:
match shape:
case Circle
(
radius
=
1
)
:
(
"Matched circle with radius 1"
)
case Rectangle
(
width
=
1
,
height
=
2
)
:
(
"Matched rectangle with width 1, height 2"
)
case _:
(
"Matched other shapes"
)
match_shape
(
Circle
(
radius
=
1
)
)
Output: Matched circle with radius 1
match_shape
(
Rectangle
(
width
=
1
,
height
=
2
)
)
Output: Matched rectangle with width 1, height 2
match_shape
(
"other"
)
Output: Matched other shapes
The output is:
匹配到半径为1的圆
匹配到宽度为1,高度为2的矩形
匹配到其他形状
Python3 Conditional Control