match Statement
3 min read ·
The
match statement is used for pattern matching in Python.
It compares a value against multiple patterns and executes the code block of the first matching case.It is similar to
switch in other languages, but more powerful and expressive.The
match statement is available from Python 3.10 onwards.Basic Syntax of match
matchstarts the comparisoncasedefines each possible pattern- No
breakis required - Only the first matching case is executed
Simple Example
- Value of
dayis matched - Case
2executes
Default Case Using _
The underscore
_ works as a default case when no pattern matches.Note
_ is executed only if no other case matches.
match with Strings
Multiple Values in One case
You can match multiple values using the
| operator.match with User Input
match with Conditions (Guards)
Guards allow you to add conditions using
if.match with Lists and Tuples
Variable Capture in case
xcaptures the value- Always matches, so use carefully
match vs if–elif
Using if–elif
Using match
match Inside Loop
Common Mistakes with match
Using break ❌
Missing Indentation ❌
Caution
break is not used inside match cases, and indentation is mandatory.
Real World Example
Real World Scenario
Traffic signal system using match
Exercise
Practice Task
- Create a calculator using
match - Print month name using month number
- Use
_as default case - Use guard conditions with
match