What is the Python equivalent for a case/switch statement? [duplicate]
How can you implement a case/switch statement in Python when it doesn’t have a built-in switch keyword? What are the best alternatives to achieve similar functionality? Let’s explore the options!
Unlike many other programming languages like C, Java, or JavaScript, Python doesn’t have a built-in switch statement. But don’t worry—there are several ways to achieve similar functionality!
1. Using if-elif-else (The Most Common Alternative)
Python developers often use if-elif-else statements to handle multiple conditions:
def switch_example(value):
if value == "apple":
return "This is a fruit!"
elif value == "carrot":
return "This is a vegetable!"
else:
return "Unknown item"
print(switch_example("apple")) # Output: This is a fruit!
- Simple and easy to read
- Best for a small number of conditions
2. Using a Dictionary (More Efficient for Constant Keys)
A dictionary can act like a switch statement by mapping keys to functions:
def fruit(): return "This is a fruit!"
def vegetable(): return "This is a vegetable!"
def unknown(): return "Unknown item"
switch_dict = {
"apple": fruit,
"carrot": vegetable
}
print(switch_dict.get("apple", unknown)()) # Output: This is a fruit!
- Faster than if-elif-else for large cases
- Avoids multiple conditional checks
3. Using match-case (Python 3.10+)
Python 3.10 introduced match-case, which works similarly to a switch statement:
def check_item(value):
match value:
case "apple":
return "This is a fruit!"
case "carrot":
return "This is a vegetable!"
case _:
return "Unknown item"
print(check_item("apple")) # Output: This is a fruit!
- More readable and structured
- Only available in Python 3.10 and newer
Each approach has its use cases—choose the one that fits your needs best!