How to use switch case in Python?
- Python does not have a built-in switch-case statement like some other programming languages.
- Alternatives include using if-elif-else statements or dictionaries for similar functionality.
- For multiple conditions, use if-elif-else constructs.
- For mapping values to functions or actions, consider using dictionaries as a switch-case substitute.
- Dictionaries associate keys with values, allowing you to define a set of actions corresponding to different cases.
- Retrieve the desired action by accessing the dictionary with the provided key.
- This approach offers flexibility and readability, enabling you to handle various cases efficiently in Python code.
Methods to implement Switch case in Python
There are various ways in which we can implement Switch case functionality in Python. Let us take a look at each one of them in detail, along with an example.
1. If-elif-else for switch case in Python
In Python, we can use if-elif-else statements to implement a switch-like behavior. Here's an example of how to use if-elif-else to implement a switch case:
Code in python
Python
def switch_case(case):
if case == 1:
print("Ninja 1")
elif case == 2:
print("Ninja 2")
elif case == 3:
print("Ninja 3")
else:
print("Invalid choice")
switch_case(1)
switch_case(2)
switch_case(3)
switch_case(4)

You can also try this code with Online Python Compiler
Run Code
Output
Ninja 1
Ninja 2
Ninja 3
Invalid choice
In this example, the switch_case() function takes an argument case and uses if-elif-else statements to check its value and execute the corresponding code block. If the case equals 1, it executes the code block under the first if statement. If the case equals 2, it executes the code block under the first elif statement. If the case equals 3, it executes the code block under the second elif statement. If the case does not match any of the conditions, it executes the code block under the else statement.
You can include as many elif statements as you need to handle different cases, and you can customize the code block under each statement to perform different tasks depending on the argument's value.
2. Dictionary Mapping for Switch case in Python
We can use dictionary mapping to implement a switch case behavior. Here's an example of how to use dictionary mapping to implement a switch case:
Code in python
Python
def switch_case(case):
switcher = {
1: "Ninja 1",
2: "Ninja 2",
3: "Ninja 3" }
result = switcher.get(case, "Invalid choice")
print(result)
switch_case(1)
switch_case(2)
switch_case(3)
switch_case(4)

You can also try this code with Online Python Compiler
Run Code
Output
Ninja 1
Ninja 2
Ninja 3
Invalid choice
In this example, the switch_case() function takes an argument case. We define a dictionary called switcher which maps each case to its corresponding value. The get() method of the dictionary is used to return the value corresponding to the case. If the case is not found in the dictionary, the method returns a default value of "Invalid choice". Finally, the function prints the value returned by the get() method.
You can add as many cases as you need to the switcher dictionary to handle different arguments, and you can customize the values to perform different tasks depending on the argument's value.
Here's another example:
Code in python
Python
def calculate(operation, num1, num2):
switcher = {
"add": num1 + num2,
"subtract": num1 - num2,
"multiply": num1 * num2,
"divide": num1 / num2
}
result = switcher.get(operation, "Invalid operation")
if result != "Invalid operation":
print(f"The result of {operation} is {result}")
else:
print(result)
calculate("add", 10, 5)
calculate("subtract", 10, 5)
calculate("multiply", 10, 5)
calculate("divide", 10, 5)
calculate("power", 10, 5)

You can also try this code with Online Python Compiler
Run Code
Output
The result of add is 15
The result of subtract is 5
The result of multiply is 50
The result of divide is 2.0
Invalid operation
In this example, the calculate() function takes three arguments operation, num1 and num2. We define a dictionary called switcher which maps each operation to its corresponding result. The get() method of the dictionary is used to return the result corresponding to the operation. If the operation is not found in the dictionary, the method returns a default value of "Invalid operation". If the result is not an "Invalid operation," the function prints the result along with the operation that was performed. Otherwise, it prints the error message.
The dictionary mapping approach can be more efficient than if-elif-else statements when you have many cases to handle, as it provides faster lookups.
3. Using Python classes
Classes can be used to implement a switch case-like behavior. Here's an example of how to use a Python class to implement a switch case:
Code in python
Python
class SwitchCase:
def case(self, case):
method_name = 'case_' + str(case)
method = getattr(self, method_name, self.case_default)
return method()
def case_1(self):
return "Ninja 1"
def case_2(self):
return "Ninja 2"
def case_3(self):
return "Ninja 3"
def case_default(self):
return "Invalid choice"
switch_case = SwitchCase()
print(switch_case.case(1))
print(switch_case.case(2))
print(switch_case.case(3))
print(switch_case.case(4))

You can also try this code with Online Python Compiler
Run Code
Output
Ninja 1
Ninja 2
Ninja 3
Invalid choice
In this example, we define a class called SwitchCase which has a method called case() that takes an argument case. The case() method dynamically calls a method corresponding to the case value using the getattr() function. If the method is not found, it calls the case_default() method.
We define methods named case_1(), case_2(), case_3(), and case_default() to handle differentcases. In this case, each method simply returns a string value corresponding to its case.
To use the SwitchCase class, we create an instance of the class called switch_case. We can then call the case() method on this instance with the appropriate argument to get the corresponding value.
You can add as many case methods as you need to the SwitchCase class to handle different cases, and you can customize each method to perform different tasks depending on the argument's value.
4. Using Python Functions and Lambdas
In Python, we can use functions and lambdas to implement a switch case-like behavior. Here's an example of how to use functions and lambdas to implement a switch case:
Code in python
Python
def case_1():
return "Ninja 1"
def case_2():
return "Ninja 2"
def case_3():
return "Ninja 3"
def switch_case(case):
switcher = {
1: case_1,
2: case_2,
3: case_3
}
result = switcher.get(case, lambda: "Invalid choice")
return result()
print(switch_case(1))
print(switch_case(2))
print(switch_case(3))
print(switch_case(4))

You can also try this code with Online Python Compiler
Run Code
Output
Ninja 1
Ninja 2
Ninja 3
Invalid choice
In this example, we define three functions called case_1(), case_2(), and case_3() to handle different cases. Each function simply returns a string value corresponding to its case.
We define a function called switch_case() which takes an argument case. We define a dictionary called switcher which maps each case to its corresponding function. The get() method of the dictionary is used to return the function corresponding to the case. If the case is not found in the dictionary, the method returns a lambda function that returns an error message.
To call the function corresponding to the case, we call the result of the get() method with empty parentheses ().
You can add as many cases as you need to the switcher dictionary to handle different arguments, and you can customize the functions to perform different tasks depending on the argument's value.
Here's another example using lambdas:
Code in python
Python
def calculate(operation, num1, num2):
switcher = {
"add": lambda: num1 + num2,
"subtract": lambda: num1 - num2,
"multiply": lambda: num1 * num2,
"divide": lambda: num1 / num2
}
result = switcher.get(operation, lambda: "Invalid operation")
return result()
print(calculate("add", 10, 5))
print(calculate("subtract", 10, 5))
print(calculate("multiply", 10, 5))
print(calculate("divide", 10, 5))
print(calculate("power", 10, 5))

You can also try this code with Online Python Compiler
Run Code
Output
15
5
50
2.0
Invalid operation
In this example, we define a function called calculate(), which takes three arguments operation, num1, and num2. We define a dictionary called switcher which maps each operation to a lambda function that performs the corresponding mathematical operation.
The get() method of the dictionary is used to return the lambda function corresponding to the operation. If the operation is not found in the dictionary, the method returns a lambda function that returns an error message.
To call the lambda function corresponding to the operation, we call the result of the get() method with empty parentheses ().
The function returns the result of the lambda function.
The function and lambda-based approach can be useful when you have a small number of cases to handle and you want to keep your code concise. However, it can be more difficult to read and maintain than the other approaches we discussed earlier.
Application of Switch Case in Python
In Python, while there isn't a native switch-case construct like in some other languages (e.g., C/C++, Java), you can achieve similar functionality using alternatives. Here are common applications of switch-case scenarios in Python:
-
Menu-driven programs: You can simulate switch-case behavior to create interactive menu-driven programs where users select options, and the program performs corresponding actions based on the chosen option.
-
State machines: Implementing state machines involves transitioning between different states based on certain conditions. While there are libraries for creating state machines in Python, you can also use dictionaries or if-elif-else constructs to emulate switch-case behavior for state transitions.
-
Dispatching functions: In scenarios where you want to execute different functions based on certain conditions or user inputs, you can use dictionaries to map input values to corresponding functions. This approach allows for dynamic function dispatching based on runtime conditions.
-
Handling user inputs or commands: When processing user inputs or commands in command-line interfaces or chatbots, you might want to execute specific actions based on the provided input. Using dictionaries or if-elif-else chains, you can efficiently handle different input cases and trigger appropriate responses or actions.
-
Configurable behavior: In applications where behavior needs to be configurable or parameterized, switch-case-like structures can be used to define different configurations or options and select the appropriate one based on runtime conditions or user preferences.
Advantages of Python Switch Case Approach
Let us list down the benefits of the Python switch case approach as follows:
-
Readability: It is easier to read and understand.
-
Consistency and Conciseness: It is more concise and takes up less code space than a series of if-elif statements.
-
Maintenance: It is easier to maintain the code using it.
-
Easy Debugging: It makes it easier to debug the code when required.
Disadvantages of Python Switch Case Approach
Let us list down the limitations of the Python switch case approach as follows:
- Readability for large chains: When there are a lot of cases, the Python switch case approach can become very difficult to read and understand. This is because each case is indented, and it can be hard to keep track of which case belongs to which statement.
-
Not available in all implementations: The Python switch case approach is not available in all Python implementations. This means that if you want to use it, you need to make sure that your implementation supports it.
-
Less efficient: The Python switch case approach can be less efficient than other approaches, such as using a dictionary or a list of if-else statements. This is because the switch case approach requires the interpreter to test each case against the value, even if it is clear that the case will not match.
Frequently Asked Questions
Is there a switch case in Python?
No, unlike other programming languages, Python does not have a switch case that is built in. But, switch case can be implemented in Python in various ways like using if-elif-else statements, dictionary mapping, Python classes, functions, and lambdas.
What is switch case statement syntax?
The syntax of the switch case statement is: switch(expression){ case value1: //code// break; //more cases//}. It also allows conditional branching based on the expression.
How many types of switch cases are there in Python?
Since Python does not have its own built-in switch case statements, there are 4 ways in which you can implement switch cases in Python - Using the if-elif-else statements, using classes, using dictionary mapping and using functions and lambdas.
How to use dictionary as switch case in Python?
To use a dictionary as a switch-case alternative in Python, define a dictionary where keys represent cases and values represent actions or results. Use the `get()` method to retrieve the value based on the given case, with an optional default value. This approach offers a concise and maintainable way to implement conditional logic.
Conclusion
Cheers if you reached here! In this blog, we saw and learned how to implement a switch case in python. We have also seen different alternatives to implement switch case in python. Further, we saw an advantage of the pythonic switch case over the C++/Java switch case.
Learning never ceases, and there is always more to learn. So, keep learning and keep growing, ninjas!
Recommended Articles -