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

  • match starts the comparison
  • case defines each possible pattern
  • No break is required
  • Only the first matching case is executed

Simple Example

  • Value of day is matched
  • Case 2 executes

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

  • x captures 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
  1. Create a calculator using match
  2. Print month name using month number
  3. Use _ as default case
  4. Use guard conditions with match