Home »
Python
Replacement for switch statement in Python
Last Updated : April 22, 2025
Python doesn't provide a built-in switch statement, unlike other programming languages. But you can implement the switch statement by using alternative approaches such as if-else chains, dictionary mapping, or the match statement introduced in Python 3.10.
Switch Case Implement Using If-Else
The if-else can be used to implement a switch-case behavior. By checking the value of a variable and executing the corresponding block of code, you can achieve similar functionality as the switch statement in other languages.
Example
The below example shows the use of if-else to simulate a switch statement:
def day_selection_if_else(day_number):
if day_number == 1:
print("Monday")
elif day_number == 2:
print("Tuesday")
elif day_number == 3:
print("Wednesday")
elif day_number == 4:
print("Thursday")
elif day_number == 5:
print("Friday")
elif day_number == 6:
print("Saturday")
elif day_number == 7:
print("Sunday")
else:
print("Invalid day")
# Calling the function with the day number 2
day_selection_if_else(2)
Output of the above example will be:
Tuesday
Switch Case Implement Using Dictionary Mapping
Another efficient way to simulate a switch statement is by using a dictionary, where keys represent case values and values represent the actions (or functions) associated with each case.
Example
The below example shows how to implement switch-case logic with dictionary mapping:
def month(i):
switch={
1:'January',
2:'February',
3:'March',
4:'April',
5:'May',
6:'June',
7:'July',
8:'August',
9:'September',
10:'October',
11:'November',
12:'December'
}
return switch.get(i, "Invalid month")
# printing
print(month(12))
print(month(13))
Output of the above example will be:
December
Invalid month
Switch Case in Python (Python 3.10 and After)
Starting from Python version 3.10, a new feature called Pattern Matching was introduced, that can be used to perform switch-case logic.
Example
The below example shows how to implement the switch-case logic using match in Python 3.10:
def day_selection(day_number):
match day_number:
case 1:
print("Monday")
case 2:
print("Tuesday")
case 3:
print("Wednesday")
case 4:
print("Thursday")
case 5:
print("Friday")
case 6:
print("Saturday")
case 7:
print("Sunday")
case _:
print("Invalid day")
# Calling the function with the day number 3
day_selection(3)
Output of the above example will be:
Wednesday
Python Switch Statement (Replacement) Exercise
Select the correct option to complete each statement about replacing the switch statement in Python.
- Python does not have a built-in ___ statement like other languages, but you can use if-elif statements as a replacement.
- To simulate a switch-case structure in Python, you can also use a dictionary with keys as ___ values.
- In Python, a common practice for replacing a switch statement is to use the ___ construct, where different expressions are mapped to corresponding values.
Advertisement
Advertisement