Update on 2024-04-15
The switch case statement presents the control flow in the program and confirms that our code is not cluttered by numerous ‘if’ statements.
In that case, the Switch-case statement is a faster and more robust programming feature that let us control the flow of the program based on the value of a variable or an expression.
They can use it to execute diverse blocks of code, depending on the mutable value during runtime. Overall, the switch is a control mechanism that examines the value kept in a variable and executes the matching case statements.
Python doesn’t have a simple switch-case concept. Coming from a Java or C++ background, we may find this to be a bit dissimilar, as Java and C++ have an inherent switch statement, here we may be amazed to know that Python language doesn’t have one. And for this we may be desirous to use a series of “if-else-if” blocks, using an “if” condition for each case of our switch statement. Because of the jump table, a switch statement is faster than an if-else-if ladder.
Instead of estimating each condition serially, it only has to look up the assessed variable once and directly jump to the suitable branch of code to execute it. We can easily understand by taking an example of how to use switch case functions:
Public Static Void Switch_Demo (String[] args {
int month = 8;
String monthString;
Switch (month) {
Case 1: monthstring = ”January”;
break;
Case 2: monthString = ”February”;
break;
Case 3: monthString = “March”;
break;
Case 4: monthString = “April”;
break;
Case 5: monthString = “May”;
break;
Case 6: monthString =”June”;
break;
Case 7: monthString =”July”;
break;
Case 8: monthString = “August”;
break;
Case 9: monthString = ”September;”
break;4
Case 10: monthString =”October”;
break;
Case 11: monthString =”November”;
break;
Case 12: monthString = “December”;
break;
default : monthString = “Invalid month”;
break;
}
System.out.println (month string);
Dictionary Mapping:
As we know that Python doesn’t have a simple switch-case statement here one way out would be to implement an if-elif-else ladder. Rather, we can also use a dictionary to map cases to the functionality, this Pythonic way to instrument a switch statement will use the dictionary mappings. If someone is aware of other programming languages, then we must be knowing that the dictionary uses key-value sets to store a set of objects in memory.
When we are using a dictionary as a substitute for switch-case statements, the keys of the key-value pair work as a case.
Here’s the Python application of the switch case functions. In this example, we create a dictionary named switcher to stock all the switch-like cases.
def switch demo(argument);
switcher ={
1: “January”;
2: “February”;
3: “March”;
4: “April”;
5: “May”;
6: “June”;
7: “July”;
8: “August”;
9: “September”;
10: “October”;
11: “November”;
12: “December”;
}
print switcher.get(argument)
Here, in this example, when we pass an argument to the switch_demo function, it is observed up against the switcher dictionary mapping. If the match is found, the associated value is printed, or else a default string (‘Invalid Month’) is printed. The default string helps in implementing the ‘default case’ of a switch statement.
A switcher is a dictionary that executes this mapping.
As we can see clearly that for values other than the one, we can mention in the switcher, it prints out “Invalid Month”. This is due to we tell it to do so using the get( ) method of a dictionary.
The values of a Python dictionary can be any type of data. So, we don’t have to restrict ourselves to using the constants, we can also use function names and lambdas as values.
For example, we can implement the above switch statement by making a dictionary of function names as values. It is easy to use this for applying the Python switch case statement. We have to follow a few steps for it.
def one():
return “January”
def two():
return “February”
def three():
return “March”
def four():
return “April”
def five():
return “May”
def six():
return “June”
def seven():
return “July”
def eight():
return “August”
def nine():
return “September”
def ten():
return “October”
def eleven():
return “November”
def twelve():
return “December”
def numbers_to_months (arguments):
switcher = {
1: one,
2: two,
3: three,
4: four,
5: five,
6: six,
7: seven,
8: eight,
9: nine,
10: ten,
11: eleven,
12: twelve
}
#Get the function from the switcher dictionary
Func = switcher.get(argument, lambda: “Invalid month”)
#Executive the function
print func()
Dictionary mapping by Python Classes:
We can use Python classes as another way of implementing switch-case statements. Class is an object constructor that has possessions and methods. Let us know this further with the help of the same example. It is relatively easy to use a class for applying the Python switch case statement. Let us do it with the given example.
class Switcher (object):
def numbers_to_months (self, argument):
“””Dispatch method”””
Method_name= ‘month_’+ str(argument
# Getthe method from ‘self’. Default to a lambda.
Method = getattr(self, method_name, lambda:”Invalid month”
# Call method as we return it
Return method()
def month_1(self):
return “January”
def month_2 (self):
return “February”
def month_3 (self):
return “March”
Based on the argument, the in-built getattr () function will save object methods with the specific name. In the above example, we used two things, the keyword lambda and the getattr () method.
We used the lambda keyword to describe an unidentified function in Python. Lambda keyword appeals to the default function when an operator enters invalid input.
The getattr () method is used to raise a function in Python.
Since we can change Python dictionaries throughout runtime like add, remove or update key-value pairs. So, we can easily alter every switch statement on the fly. Here is an example:
def zer():
return “zero”
def one():
return “one”
def two():
return “two”
switcher ={
0: zero,
1: one,
2: two
}
Def numbers_to_strings(arguments):
# Get the function from switcher dictionary
Func = switcher. get(argument, “nothing”)
# Execute the function
Return func()
Input: numbers_to_strings(1)
Output: One
Input: switchet[1]=two #changing the switch case
Input: numbers_to_strings(1)
Output: Two
Switch case is a very useful programming concept that not only delivers better performance than an if-else statement but also leaves us with a more practicable code. In this article, we have learned about switch-case functions, after we discuss what are the substitutions to these switch-case functions, and how to use them. Hence as explained, we conclude that still, Python does not have an in-built switch case function, we can always use these alternatives like using dictionary mapping instead of placing a switch case to implement them in our way.
Related Articles
Trending News
Copyright @2024.www.collegedisha.com. All rights reserved