codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

© 2026 codingstuff.io. All rights reserved.

Built with ❤️ for developers everywhere

/
/
All Tutorials
🐍

Python Programming

15 / 68 topics
14Python if...else Statement15Python Match Statement16Python for Loop & range()17Python while Loop18Python break, continue, and pass
Tutorials/Python Programming/Python Match Statement
🐍Python Programming

Python Match Statement

Updated 2026-05-15
20 min read

Python Match Statement

Introduction

In this tutorial, we'll explore the match statement introduced in Python 3.10, which provides a powerful and flexible way to perform pattern matching. This feature is particularly useful for handling multiple conditions based on different patterns, making your code more readable and concise compared to traditional if-elif-else chains. Whether you're working with simple data types or complex objects, the match statement can simplify your control flow logic.

Core Content

Understanding the Match Statement

The match statement is a generalization of the switch statements found in other programming languages like C, Java, and JavaScript. It allows you to match a variable against multiple patterns and execute different blocks of code based on which pattern matches.

Basic Syntax

Python
1match variable:
2 case pattern1:
3 # Code block for pattern1
4 case pattern2:
5 # Code block for pattern2
6 case _:
7 # Default case (wildcard)
  • match: The keyword used to start the match statement.
  • variable: The expression to be matched against patterns.
  • case: Used to specify a pattern to match.
  • _: A wildcard pattern that matches any value, similar to default in other languages.

Example: Basic Match Statement

Let's start with a simple example where we match an integer against different cases.

basic_match.py
1def match_number(n):
2 match n:
3 case 1:
4 return "One"
5 case 2:
6 return "Two"
7 case 3:
8 return "Three"
9 case _:
10 return "Other"
11
12print(match_number(1)) # Output: One
13print(match_number(4)) # Output: Other
Output
One
Other

In this example, the function match_number takes an integer n and returns a string based on its value. The match statement checks each case in order until it finds a match or reaches the default case.

Wildcard Patterns

The underscore _ acts as a wildcard pattern, matching any value. It's often used to handle cases that don't require specific handling.

Example: Using Wildcards

Here's an example where we use wildcards to handle multiple values in a single case.

wildcard_match.py
1def match_letter(letter):
2 match letter:
3 case 'a' | 'e' | 'i' | 'o' | 'u':
4 return "Vowel"
5 case _:
6 return "Consonant"
7
8print(match_letter('a')) # Output: Vowel
9print(match_letter('b')) # Output: Consonant
Output
Vowel
Consonant

In this example, the match_letter function checks if a given letter is a vowel or consonant using a wildcard pattern to match any of the vowels.

Guard Clauses

Guard clauses allow you to add additional conditions within a case. These conditions are specified after an if keyword and must evaluate to True for the case to be executed.

Example: Using Guard Clauses

Let's see how guard clauses can be used to refine pattern matching.

guard_clause_match.py
1def match_temperature(temp):
2 match temp:
3 case t if t < 0:
4 return "Freezing"
5 case t if 0 <= t < 20:
6 return "Cold"
7 case t if 20 <= t < 30:
8 return "Mild"
9 case t if 30 <= t < 40:
10 return "Warm"
11 case _:
12 return "Hot"
13
14print(match_temperature(-5)) # Output: Freezing
15print(match_temperature(15)) # Output: Cold
16print(match_temperature(25)) # Output: Mild
17print(match_temperature(35)) # Output: Warm
18print(match_temperature(45)) # Output: Hot
Output
Freezing
Cold
Mild
Warm
Hot

In this example, the match_temperature function categorizes temperatures into different ranges using guard clauses. Each case checks a specific range and returns a corresponding description.

Class Patterns

Class patterns allow you to match against instances of classes and extract their attributes. This is particularly useful for handling complex data structures like objects.

Example: Using Class Patterns

Let's see how class patterns can be used to match against custom objects.

class_pattern_match.py
1class Point:
2 def __init__(self, x, y):
3 self.x = x
4 self.y = y
5
6def describe_point(p):
7 match p:
8 case Point(x=0, y=0):
9 return "Origin"
10 case Point(x=0, y=y):
11 return f"Y-axis at {y}"
12 case Point(x=x, y=0):
13 return f"X-axis at {x}"
14 case Point():
15 return f"Point at ({p.x}, {p.y})"
16 case _:
17 return "Not a point"
18
19print(describe_point(Point(0, 0))) # Output: Origin
20print(describe_point(Point(0, 5))) # Output: Y-axis at 5
21print(describe_point(Point(3, 0))) # Output: X-axis at 3
22print(describe_point(Point(4, 7))) # Output: Point at (4, 7)
Output
Origin
Y-axis at 5
X-axis at 3
Point at (4, 7)

In this example, the describe_point function uses class patterns to match against instances of the Point class. It checks for specific points like the origin and axes, and provides a general description for other points.

Practical Example

Let's create a practical example that demonstrates the use of the match statement in a real-world scenario. We'll build a simple command-line tool that interprets user commands.

command_parser.py
1def parse_command(command):
2 match command.split():
3 case ["start", service]:
4 return f"Starting {service}..."
5 case ["stop", service]:
6 return f"Stopping {service}..."
7 case ["restart", service]:
8 return f"Restarting {service}..."
9 case ["status"]:
10 return "Checking status..."
11 case _:
12 return "Unknown command"
13
14def main():
15 while True:
16 user_input = input("Enter a command: ")
17 if user_input.lower() == "exit":
18 break
19 print(parse_command(user_input))
20
21if __name__ == "__main__":
22 main()

This script defines a parse_command function that uses the match statement to interpret different commands. The main function runs an interactive loop where users can enter commands, and the program responds accordingly.

Summary

ConceptDescription
Basic Match StatementMatches a variable against multiple patterns using case.
Wildcard PatternsUses _ to match any value.
Guard ClausesAdds additional conditions within a case using if.
Class PatternsMatches against instances of classes and extracts their attributes.
  • The match statement provides a cleaner and more readable way to handle multiple conditions compared to if-elif-else chains.
  • Wildcard patterns (_) are useful for handling cases that don't require specific handling.
  • Guard clauses allow you to refine pattern matching with additional conditions.
  • Class patterns enable matching against objects and extracting their attributes.

What's Next?

In the next tutorial, we'll explore loops in Python, starting with the for loop. We'll learn how to use the range() function to generate sequences of numbers and apply them in various scenarios. This will build on our understanding of control flow and prepare us for more complex programming tasks.

Stay tuned!


PreviousPython if...else StatementNext Python for Loop & range()

Recommended Gear

Python if...else StatementPython for Loop & range()