HubFirms : Blog -How to implement a switch-case statement in Python

How to implement a switch-case statement in Python

How to implement a switch-case statement in Python

Switch-case explanation is an incredible programming highlight that permits you control the progression of your program dependent on the estimation of a variable or an articulation. You can utilize it to execute various squares of code, contingent upon the variable incentive during runtime. Here's a case of a switch proclamation in Java.

public static void switch_demo(String[] args) {
        int month = 8;
        String monthString;
        switch (month) {
            case 1:  monthString = "January";
            case 2:  monthString = "February";
            case 3:  monthString = "March";
            case 4:  monthString = "April";
            case 5:  monthString = "May";
            case 6:  monthString = "June";
            case 7:  monthString = "July";
            case 8:  monthString = "August";
            case 9:  monthString = "September";
            case 10: monthString = "October";
            case 11: monthString = "November";
            case 12: monthString = "December";
            default: monthString = "Invalid month";
Java vs Python – What’s better for your project?

Here's the means by which it works: 

1.Compiler produces a hop table for switch case explanation 

2.The switch variable/articulation is assessed once 

3.Switch proclamation looks into the assessed variable/articulation in the hop table and straightforwardly chooses which code square to execute. 

4.If no match is discovered, at that point the code under default case is executed 

In the above model, contingent upon the estimation of variable month, an alternate message will be shown in the standard yield. For this situation, since the month=8, 'August' will be imprinted in standard yield. 

Switch statement 

Albeit mainstream dialects like Java and PHP have in-fabricated switch proclamation, you might be astonished to realize that Python language doesn't have one. All things considered, you might be enticed to utilize a progression of if-else-if squares, utilizing an if condition for each instance of your switch articulation. 

Be that as it may, as a result of the hop table, a switch articulation is a lot quicker than an if-else-if stepping stool. Rather than assessing each condition successively, it just needs to look into the assessed variable/articulation once and legitimately bounce to the fitting part of code to execute it. 

Step by step instructions to actualize switch proclamation in Python 

The Pythonic approach to execute switch articulation is to utilize the amazing lexicon mappings, otherwise called acquainted exhibits, that give straightforward coordinated key-esteem mappings. 

Here's the Python usage of the above switch articulation. In the accompanying model, we make a word reference named switcher to store all the switch-like cases.[Top 100 Python Interview Questions and Answers]

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, "Invalid month")

In the above model, when you pass a contention to the switch_demo work, it is gazed upward against the switcher lexicon mapping. On the off chance that a match is discovered, the related worth is printed, else a default string ('Invalid Month') is printed. The default string helps actualize the 'default case' of a switch articulation. 

Word reference mapping for capacities 

Here's the place it gets all the more fascinating. The estimations of a Python lexicon can be of any information type. So you don't need to limit yourself to utilizing constants (whole numbers, strings), you can likewise utilize capacity names and lambdas as qualities. 

For instance, you can likewise actualize the above switch articulation by making a word reference of capacity names as qualities. For this situation, switcher is a word reference of capacity names, and not strings.

An Introduction to the Java Collections Framework
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(argument):
    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 switcher dictionary
    func = switcher.get(argument, lambda: "Invalid month")
    # Execute the function
    print func()

Despite the fact that the above capacities are very basic and just return strings, you can utilize this way to deal with execute expound squares of code inside each capacity. 

Truth be told, in case you're calling techniques on articles, you can even utilize a dispatch strategy to powerfully figure out which capacity should be called during runtime.[Top 10 Python Interview Questions and Answers]

class Switcher(object):
    def numbers_to_months(self, argument):
        """Dispatch method"""
        method_name = 'month_' + str(argument)
        # Get the method from 'self'. Default to a lambda.
        method = getattr(self, method_name, lambda: "Invalid month")
        # Call the 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"

In light of the passed contention, the in-fabricated getattr() capacity will recover object strategies with the specific name. 

Input: a=Switcher()
Input: a.numbers_to_months(1)
Output: January

Advantage of Python’s approach

Since you can modify Python word references during runtime (include, evacuate or update key-esteem sets), you can undoubtedly change your very switch articulation on the fly. Here's a model, 

def zero():
    return "zero"
def one():
    return "one"
def two():
    return "two"
switcher = {
        0: zero,
        1: one,
        2: two
def numbers_to_strings(argument):
    # Get the function from switcher dictionary
    func = switcher.get(argument, "nothing")
    # Execute the function
    return func()
Input: numbers_to_strings(1)
Output: One
Input: switcher[1]=two #changing the switch case
Input: numbers_to_strings(1)
Output: Two

Switch case is an exceptionally helpful programming develop that not just gives preferred execution over an if-else articulation yet in addition leaves you with a progressively sensible code. On the off chance that you've felt restricted by the absence of switch articulation in Python, at that point ideally, the above instructional exercise will enable you to actualize it.

How to Create an Array List in Java

Author Biography.

Hub Firms
Hub Firms

HubFirms is one of the world’s largest online publications that delivers an international perspective on the latest news about Internet technology, business and culture.

Related Posts