- Aliases
- and operator
- Booleans
- Classes
- Code blocks
- Comments
- Conditional statements
- Console
- datetime module
- Dictionaries
- enum
- enumerate() function
- Equality operator
- False
- Floats
- For loops
- Formatted strings
- Functions
- Greater than operator
- Greater than or equal to operator
- If statement
- in operator
- Indices
- Inequality operator
- Integers
- Less than operator
- Less than or equal to operator
- List append() method
- List insert() method
- List pop() method
- List sort() method
- Lists
- map() function
- Match statement
- Modules
- None
- not operator
- or operator
- Parameters
- print() function
- range() function
- Regular expressions
- requests Library
- return statement
- round() function
- Sets
- String join() method
- String replace() method
- String split() method
- Strings
- time.sleep() function
- True
- try...except statement
- Tuples
- Variables
- While loops
PYTHON
Python Match Statement: A Versatile Switch-Case in Python
The Python match statement allows you to compare values against patterns. Its structure is similar to the switch-case statement in other programming languages.
How to Use the Python Match Statement
The Python syntax starts with the match
keyword, followed by an expression. Inside the code block, case statements define the patterns to compare against.
match expression:
case pattern1:
# Execute if pattern1 fits
case pattern2:
# Execute if pattern2 fits
case _:
# Execute if no pattern fits (default case)
match
: The keyword to initiate a switch-case statement in Python.expression
: The value you want to test against the patterns.case
: The keyword to start a case block with a pattern to test against. If the pattern fits, the corresponding block of code executes._
: The wildcard character defines the default case when no other cases fit the specified patterns.
Basic Usage
def match_value(x):
match x:
case 1:
return "One"
case 2:
return "Two"
case _:
return "Other"
When to Use match
in Python
Simplifying Multiple Conditions
You can use the equivalent of the switch-case statement in Python to simplify complex conditionals. Instead of using multiple if-elif statements, you can use cases to check against.
def http_status_code(status):
match status:
case 200:
return "OK"
case 404:
return "Not Found"
case 500:
return "Server Error"
case _:
return "Unknown Status"
Validating User Input
The statement is also helpful for checking sequence patterns in user input. For example, you can match string patterns to ensure the input meets certain conditions.
def validate_input(user_input):
match user_input:
case "yes":
return "You agreed!"
case "no":
return "You disagreed!"
case _:
return "Invalid response"
Handling Multiple Data Types
Using cases to test against is also useful when handling different data types. This allows you to process different kinds of inputs efficiently.
def handle_input(data):
match data:
case int():
return f"Integer: {data}"
case str():
return f"String: {data}"
case _:
return "Unknown data type"
Managing Complex Data Structures
You can also Python-switch through cases for more complex data structures like lists, tuples, or dictionaries.
def process_coordinates(coordinates):
match coordinates:
case (x, y):
return f"Coordinates: x={x}, y={y}"
case _:
return "Unknown format"
Examples of Using Switch-Case in Python
Command-Line Tools
Command-line tools or chatbots often use the match statement to identify and respond to specific commands. This makes it easy to route commands to the appropriate handlers.
def handle_command(command):
match command:
case "start":
return "Starting the process..."
case "stop":
return "Stopping the process..."
case "help":
return "Showing help documentation..."
case _:
return "Unknown command"
Web Application Routing
In web development, frameworks often need to route URLs to specific handlers. You can streamline the routing process by using a match statement to define cases for each web page.
def route(path):
match path:
case "/home":
return "Home Page"
case "/about":
return "About Page"
case "/contact":
return "Contact Page"
case _:
return "404 Not Found"
File Type Detection in File Processing
A file processing application might need to detect file types and perform different actions based on the file extension. This is where match
can help you easily sort and handle files.
def handle_file_extension(extension):
match extension:
case ".txt":
return "Text file"
case ".jpg" | ".png":
return "Image file"
case ".pdf":
return "PDF file"
case _:
return "Unknown file type"
Data Analytics Applications
In data analytics, you can use the statement to categorize data points based on their value range or category.
def categorize_data_point(value):
match value:
case value if value < 0:
return "Negative"
case value if value >= 0 and value <= 10:
return "Low"
case value if value > 10:
return "High"
Learn More About the Python Match Statement
Switch-Case Statements in Python and Other Programming Languages
Other programming languages use so-called switch-case statements for similar purposes. However, traditional switch statements often only work with primitive data types like integers and strings.
Python allows more complex cases with data structures like lists, tuples, and dictionaries. Therefore, Python's implementation of the switch-case statement is more versatile than other such mechanisms.
Matching Objects in Python
Python's match statement works well with data classes, allowing you to look for overlaps of object properties.
from dataclasses import dataclass
@dataclass
class Point:
x: int
y: int
def describe_point(point):
match point:
case Point(x=0, y=0):
return "Origin"
case Point(x, y):
return f"Point at ({x}, {y})"
Wildcard Patterns in Python
The wildcard pattern (_
) acts as a catch-all case. It works like a default case in a traditional switch statement. For example, you can use a wildcard pattern to handle any unexpected input in your program.
def match_numbers(num):
match num:
case 1:
return "One"
case 2:
return "Two"
case _:
return "Other"
Regular Expressions with Python Match
You can combine Python’s re.match()
function with the match
statement to compare strings based on regular expressions. This is especially useful if you have a string pattern to match or test against, such as validating email formats.
import re
def check_email(email):
match email:
case re.match(r"\\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Z|a-z]{2,}\\b", email):
return "Valid email"
case _:
return "Invalid email"
Combining Match with Loops
You can combine match statements with loops to handle complex data or repetitive tasks. This is especially useful when processing multiple values at once or dealing with collections.
data = [1, 'hello', 3.5, 'Python']
for item in data:
match item:
case int():
print(f"Integer: {item}")
case str():
print(f"String: {item}")
case _:
print(f"Other type: {item}")
Match with Guards
You can use guards within your cases to further control when a case executes. A guard is an additional condition you can attach to a case that needs to evaluate to True
for the case to trigger.
def grade_student(score):
match score:
case score if score >= 90:
return "A"
case score if score >= 80:
return "B"
case score if score >= 70:
return "C"
case _:
return "F"
Adding guards to cases can help simplify control flow in scenarios where you need to check additional conditions.
Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.