Unlike some other programming languages, Python does not include a built-in "case" or "switch" statement. However, similar functionality can be achieved using Python's control flow structures, such as if-elif-else statements and the use of dictionaries. In this section, we'll look at the various Python options for creating a "case" or "switch" statement equivalent.
Python equivalent for a case/switch statement
1. Using Dictionary Mapping
Dictionaries are much like lists with an extra parameter called keys. Recall, how in lists and strings, we used the index as the parameter to access each element of the string/list. The main differentiating factor between a list and a dictionary would be, that instead of the index we use keys to access the elements of a dictionary (or values to access keys, works both ways).
Also, unlike an index, keys can be of any data type varying from integer to string. This makes them more flexible to use.
In this example, the dictionary my_dict
maps the keys 'A', 'B', and 'C' to the values 1, 2, and 3 respectively. The code then uses the key 'B' to retrieve the corresponding value 2 from the dictionary and assigns it to the variable mapped_value
.
# Define the dictionary
my_dict = {'A': 1, 'B': 2, 'C': 3}
# Use the dictionary to map a value
original_value = 'B'
mapped_value = my_dict[original_value]
print(mapped_value)
Output
2
Alternatively, you can use get()
method to access the value of a key in a dictionary, if the key is not present in the dictionary it will return None, and if you pass an default value as a second parameter, it will return that default value instead of None, for example:
original_value = 'D'
mapped_value = my_dict.get(original_value, "Key not found.")
print(mapped_value)
Output
Key not found.
You can also use a for loop to iterate through all the key-value pairs in a dictionary:
for key, value in my_dict.items():
print(key, value)
Output:
A 1
B 2
C 3
You can also use the keys() and values() methods to access just the keys or just the values in a dictionary, respectively:
keys = my_dict.keys()
values = my_dict.values()
This can be useful when you want to perform an operation on all the keys or values in a dictionary.
2. Using if-else statement
In Python, the if-elif-else
statement can be used as a substitute for a case/switch
statement found in other programming languages. Here is an example of using if-elif-else
for a simple case/switch statement:
elif case == 3:
print("Case 3")
else:
print("Default Case")
switch_example(1) # prints "Case 1"
switch_example(2) # prints "Case 2"
switch_example(3) # prints "Case 3"
switch_example(4) # prints "Default Case"
Alternatively, python has the dict.get()
method that can be used to achieve the same functionality of switch statement.
def switch_example(case):
options = {1: "Case 1",
2: "Case 2",
3: "Case 3"}
print(options.get(case, "Default Case"))
switch_example(1) # prints "Case 1"
switch_example(2) # prints "Case 2"
switch_example(3) # prints "Case 3"
switch_example(4) # prints "Default Case"
3. Using Class
In Python, you can use a class to create a more robust and reusable version of a case/switch statement. Here is an example of using a class for a simple case/switch statement:
class Switch:
def __init__(self, case):
self.case = case
def cases(self):
return {
1: self.case1,
2: self.case2,
3: self.case3
}
def case1(self):
print("Case 1")
def case2(self):
print("Case 2")
def case3(self):
print("Case 3")
def default(self):
print("Default Case")
def run(self):
return self.cases().get(self.case, self.default)()
sw = Switch(1)
sw.run() # prints "Case 1"
sw = Switch(2)
sw.run() # prints "Case 2"
sw = Switch(3)
sw.run() # prints "Case 3"
sw = Switch(4)
sw.run() # prints "Default Case"
The above example creates a class called Switch
, which has a constructor that takes in a case
argument. The class also has a cases()
method that returns a dictionary containing the possible cases and their corresponding methods. The run()
method is used to execute the appropriate case method based on the case argument passed to the constructor.
It's important to note that this approach also allows you to encapsulate the behavior of each case in a single location, making it easy to change or add new cases without affecting the rest of the code. Additionally, it makes the code more readable and maintainable.
Conclusion
Finally, the use of if-elif-else statements is the Python equivalent of a case/switch statement. These statements, like a case/switch statement in other programming languages, allow for the execution of different code blocks based on the value of a given expression. In addition, dictionaries and functions can be used as substitutes in more complex cases. Overall, Python's flexibility and expressiveness enable a variety of approaches to achieving the same functionality as a case/switch statement.