What is the Python equivalent for a case/switch statement?
Categories:
Mastering Conditional Logic: Python's Equivalent to Case/Switch Statements

Explore various Pythonic approaches to implementing switch-like functionality, from traditional if/elif/else to the modern match
statement.
Unlike many other programming languages like C++, Java, or JavaScript, Python traditionally does not have a built-in switch
or case
statement. This often leads developers new to Python to wonder how to handle multiple conditional branches efficiently. Fortunately, Python offers several elegant and Pythonic ways to achieve similar functionality, ranging from simple if/elif/else
constructs to dictionary mapping and, more recently, the powerful match
statement introduced in Python 3.10.
The Traditional Approach: If/Elif/Else
The most straightforward and universally understood way to implement conditional logic in Python is using a series of if
, elif
(else if), and else
statements. This method is perfectly valid and often preferred for simple cases or when the conditions are not based solely on the value of a single variable.
def get_day_name_if_elif(day_number):
if day_number == 1:
return "Monday"
elif day_number == 2:
return "Tuesday"
elif day_number == 3:
return "Wednesday"
elif day_number == 4:
return "Thursday"
elif day_number == 5:
return "Friday"
elif day_number == 6:
return "Saturday"
elif day_number == 7:
return "Sunday"
else:
return "Invalid day number"
print(get_day_name_if_elif(3)) # Output: Wednesday
Using if/elif/else for conditional branching
if/elif/else
is simple and readable, it can become verbose and less efficient for a large number of conditions, especially when checking the same variable repeatedly.Dictionary Mapping for Cleaner Code
For scenarios where you need to map specific input values to corresponding actions or results, a dictionary can serve as an excellent and more scalable alternative to a long if/elif/else
chain. This approach is particularly effective when the 'cases' are static and known beforehand.
def get_day_name_dict(day_number):
day_map = {
1: "Monday",
2: "Tuesday",
3: "Wednesday",
4: "Thursday",
5: "Friday",
6: "Saturday",
7: "Sunday"
}
return day_map.get(day_number, "Invalid day number")
print(get_day_name_dict(5)) # Output: Friday
Implementing switch-like logic using a dictionary
flowchart TD A[Start Function] --> B{Input: day_number} B --> C{"day_map.get(day_number)"} C -->|Key Found| D[Return Mapped Value] C -->|Key Not Found| E[Return Default Value] D --> F[End] E --> F[End]
Flowchart of dictionary-based switch logic
The Modern Approach: The match
Statement (Python 3.10+)
Python 3.10 introduced the match
statement, also known as structural pattern matching, which provides a powerful and explicit way to implement switch-like behavior. It goes beyond simple value matching, allowing for complex pattern matching, including sequences, dictionaries, and even custom classes.
def process_command(command):
match command:
case "start":
return "Starting service..."
case "stop":
return "Stopping service..."
case "restart":
return "Restarting service..."
case "status":
return "Checking service status..."
case _:
return f"Unknown command: {command}"
print(process_command("start")) # Output: Starting service...
print(process_command("status")) # Output: Checking service status...
print(process_command("pause")) # Output: Unknown command: pause
Using the match
statement for command processing
match
statement is only available in Python 3.10 and later. If you are working with older Python versions, you will need to use if/elif/else
or dictionary mapping.Advanced Pattern Matching with match
The match
statement's true power lies in its ability to perform structural pattern matching. This allows you to match against more complex data structures and extract values directly.
def handle_event(event):
match event:
case {"type": "click", "x": x, "y": y}:
return f"Mouse clicked at ({x}, {y})"
case {"type": "keypress", "key": key, "modifiers": mods}:
return f"Key '{key}' pressed with modifiers: {mods}"
case ["error", code, message]:
return f"Error {code}: {message}"
case _:
return "Unknown event type"
print(handle_event({"type": "click", "x": 100, "y": 200}))
# Output: Mouse clicked at (100, 200)
print(handle_event(["error", 404, "Not Found"]))
# Output: Error 404: Not Found
Advanced pattern matching with dictionaries and lists
The _
(underscore) acts as a wildcard pattern, similar to the default
case in other languages, catching any value that doesn't match previous patterns.