PythonConditional Statements
Match
Python 3.10 introduced the match statement, a modern and more readable alternative to long if-elif-else chains.
It is similar to the switch-case found in languages like C or Java, but more powerful, cleaner, and easier to maintain.
Why Use match?
- It provides a concise and readable way to compare a variable against multiple values.
- Eliminates repetitive conditions seen in long
if-elif-elseblocks. - Enhances code clarity and reduces verbosity.
- Performs direct value matching without needing expressions like
num == 1. - Supports a fallback case using
case _:, which behaves like anelseordefaultclause.

Syntax of Match-Case
match variable:
case value1:
# statements
case value2:
# statements
case _:
# default caseExample: Number to Word Conversion
num = 3
match num:
case 1:
print("One")
case 2:
print("Two")
case 3:
print("Three")
case 4:
print("Four")
case 5:
print("Five")
case _:
print("Incorrect")Output
Three- Only the matching
caseexecutes. - The
case _:block handles all unmatched values (default case).
Comparison With if-elif-else
| Feature | if-elif-else | match |
|---|---|---|
| Syntax | More verbose | More concise |
| Readability | Lower for many conditions | Cleaner for value checks |
| Default behavior | else | case _ |
| Flexibility | Expression-based logic | Pattern-based, direct value matching |
Key Advantages of Match
- Provides a much cleaner alternative to long or deeply nested if-elif-else structures.
- Best suited for direct value comparisons such as menu selections, status checks, and enum-like options.
case _serves as the default fallback, handling any unmatched values.- Offers better readability, maintainability, and scalability when dealing with large sets of conditions.
Summary
matchoffers a cleaner and modern alternative to long if-elif chains, making code easier to read and maintain.- It enables direct and structured value matching, improving clarity in decision-making logic.
case _acts as the default fallback, handling all unmatched values gracefully.- Reduces boilerplate and enhances code organization, especially in programs with many condition checks.
Written By: Muskan Garg
How is this guide?
Last updated on
