in Python some alternatives that can achieve similar switch statement.
Published on Aug. 22, 2023, 12:15 p.m.
As I mentioned earlier, Python does not have a built-in switch statement. However, there are some alternatives that can achieve similar functionality.
use nested if-else statements
One common solution is to use nested if-else statements to test each possible condition individually. Another alternative is to use a dictionary to emulate a switch statement. Here is an example of using nested if-else statements:
def switch_case(case):
if case == 'case1':
return 'Result 1'
elif case == 'case2':
return 'Result 2'
elif case == 'case3':
return 'Result 3'
else:
return 'Invalid case'
print(switch_case('case2'))
In this example, we define a function called switch_case()
that takes a single argument called case
. We then use if-else statements to test each possible case individually. If the given case matches one of the cases, we return the corresponding result. If the given case is not found, we return ‘Invalid case’.
use a dictionary to emulate a switch statement.
Using a dictionary, as I mentioned earlier, can also be used to emulate a switch statement.
Another way is to use a dictionary to emulate a switch statement. Here’s an example using a dictionary:
def switch_case(case):
return {
'case1': 'Result 1',
'case2': 'Result 2',
'case3': 'Result 3',
}.get(case, 'Invalid case')
print(switch_case('case2'))
In this example, we define a function called switch_case()
that takes a single argument called case
. We then define a dictionary where each key represents a case, and each value represents the result for that case. We use the get()
method of the dictionary to look up the value for the given case. If the given case is not found, we return the string ‘Invalid case’.