python switch case

Introduction 

Computer software programming language engineers who have used C, C++, and Java programming languages while developing software have used switch-case statements. But in the case of Python, they are unable to use switch-case statements because they are not defined in Python. 

In this article, there is much emphasis on the switch case statement because there are many factors that clarify why the switch case statement has the upper hand in comparison to the if-else statement. The factors are:

  • In comparison with the if-else ladder, a switch statement works much faster. It happens because of a jump table that is generated by the compiler for a switch during compilation. As an outcome, during execution, rather than checking which case is satisfied, it only decides which case has to be executed.
  • Switch statements are cleaner than if-else chains. 
  • They better express the semantics of the code than if-else chains. 
  • They allow less room for errors than if-else chains.  
  • They reduce duplication and potentially improve performance.
  • It provides more readability in comparison with if-else statements.

Just imagine, if programmers get an alternative way of writing codes than those complex if-else statements in Python, then how would it be? If programmers want to be safe from cluttering code using if-else statements, then they should think of using switch case statements in their coding. The advantages of using switch case statements are already mentioned above.

Python doesn’t provide switch-case statements like C, C++, Java, and Ruby, but it offers some provisions to make these statements work.

For example, Python enables programmers to create their code snippets that work like Python Switch case statements in other programming languages. 

This article is intended to provide ways to implement switch-case statements in Python.

Switch Statement in Python

The switch can be defined as a control mechanism that is used to test the value stored in a variable and to execute the corresponding case statements. The function of the switch case statement is to introduce control flow in the program and to ensure that code is not cluttered by multiple ‘if’ statements. Thus code looks diligent and transparent to viewers. This wonderful programming feature is used by programmers for the implementation of the control flow in their code. The work of the switch case statement is to compare the values specified in the case statements with variables in the code. 

Why Switch-case Statement Not In Python?

In Python, switch-case statements don’t exist because of unsatisfactory proposals. Many proposals failed as they could not work well with Python’s syntax and established coding style.

Most programming languages provide switch case functions because they lack proper mapping constructs, and the reason is that a value can not be mapped into a function. 

But in the Python case, with the help of a mapping table (dict), it is possible to map a certain value to a certain function. Performance-wise the Python dictionary will be more efficient than any other solution.

In Python, in place of the switch case function, a switcher is used. In Python, the switcher is also known as dictionary mapping. 

Unlike other languages where a switch case is used in which cases are executed according to the user’s input, in the switcher, the available options are executed according to the user’s input.

How to Implement Python Switch Case Statement?

For the programmers who have coded in the languages such as C, C++, or Java, it looks odd that Python doesn’t support switch-case statements. In place of it, Python offers many workarounds such as a dictionary, Python lambda functions, or Python classes for the implementation of switch-case statements.

Programmers should check PEP 3103 so that they can understand the exact reason why Python is not provided with the switch case statement. 

What Is PEP 3103?

In Python, PEP stands for Python Enhancement Proposal, and a lot of them are available. A PEP can be defined as a document in which new features for Python are included. The document also documents aspects of Python, like design and style, for the community.

PEP 3103, version: $Revision$, is a switch/case statement, and it was created on 25 Jun 2006 and posted on 26 Jun 2006. 

This PEP was brought into the existence to introduce canonical names for the many variants for different aspects of the syntax and semantics, such

as “alternative 1”, “school II”, “option 3” and more.

This proposal was rejected because of no popular support for it.

Before digging more deeper into these alternatives, it is good to see the typical functioning of switch-case statements in the rest of the programming languages.

Let’s see the below-mentioned program made using the C programming language:

——————————————

switch (DayOfWeek){
    case 1:
        printf(“%s”, Monday);
        break;
    case 2:
        printf(“%s”, Tuesday);
        break;
    case 3:
        printf(“%s”, Wednesday);
        break;
    case 4:
        printf(“%s”, Thursday);
        break;
    case 5:
        printf(“%s”, Friday);
        break;
    case 6:
        printf(“%s”, Saturday);
        break;
    case 7:
        printf(“%s”, Sunday);
        break;
default:
        printf(“Incorrect Day”);
        break;
}

——————————————

Explanation 

In the program mentioned above, if the input is “2,” then the output result will be “Tuesday,” and if the input is “6,” then the output result will be “Saturday”. When the input is out of 1 to 7, then in this case, the output result will be “Incorrect Day”.

Alternatives of the switch-case functions

Now let’s move towards the alternatives of the switch case functions in Python and learn with examples how these alternatives function.

1. Using Dictionary Mapping

The programmers who know other programming languages must have been knowing how a dictionary functions. To store a group of objects in memory, the dictionary uses key-value pairs. In Python, when programmers use a dictionary as an alternative to switch-case statements, the keys of the key-value pair work as a case.

The below-mentioned example demonstrates the implementation of the switch case statement using a dictionary.

In this program, a function month() is defined to print which week, a week of the month is.

Let’s start creating case statements first and then write individual functions for each case. Ensure that a function is written to handle the default case. 

——————————————

def monday():
   
    return “Monday”
def tuesday():
    return “Tuesday”
def wednesday():
    return “Wednesday”
def thursday():
    return “Thursday”
def friday():
    return “Friday”
def saturday():
    return “Saturday”
def sunday():
    return “Sunday”
def default():
    return “Incorrect Day”

——————————————

The next action is to create a dictionary object in Python and store all the functions that have been defined in the program.

——————————————

switcher = {
    0: ‘monday’,
    1: ‘tuesday’,
    2: ‘wednesday’,
    3: ‘thursday’,
    4: ‘friday’,
    5: ‘saturday’,
    6: ‘sunday’,
     }

——————————————

In the last action, a switch function will be created in the program that will accept an integer as an input, will perform a dictionary lookup, and invoke the corresponding functions.

——————————————

def day(DayOfWeek):
   
 return 
     switcher.get(default)()

——————————————

The complete code will look as follows:

——————————————

def monday():
    return “Monday”
def tuesday():
    return “Tuesday”
def wednesday():
    return “Wednesday”
def thursday():
    return “Thursday”
def friday():
    return “Friday”
def saturday():
    return “Saturday”
def sunday():
    return “Sunday”
def default():
    return “Incorrect Day”
    switcher = {
    0: ‘monday’,
    1: ‘tuesday’,
    2: ‘wednesday’,
    3: ‘thursday’,
    4: ‘friday’,
    5: ‘saturday’,
    6: ‘sunday’,
     }
def day(DayOfWeek):
return switcher.get(DayOfWeek, default)()
print(switch(1))
print(switch(0))

——————————————

The above code prints the following output:

——————————————

Tuesday 

Monday 

——————————————

2. Using Python Classes

Python classes are also an available alternative that can be used to implement switch-case statements in Python.

A class can be defined as an object constructor that contains properties and methods. 

To understand this alternative, let’s use the example mentioned above again.

In this process, a switch method will be defined inside a Python switch class.

Example

In the first action,  a switch method will be defined inside a Python switch class that will accept a week of the month as an argument, and then this will be converted into a string.

——————————————

class PythonSwitch:
def day(DayOfWeek):
        default = “Incorrect Day”
        return getattr(self, ‘case_’ + str(DayOfWeek), lambda: default)()

——————————————

Note: Two things are used in the above example: keyword lambda and getattr() method. 

The Lambda keyword is used to define an anonymous function in Python. The function of the Lambda keyword is to invoke the default function at the time an invalid input is entered by a user.

The function of the getattr() method is to invoke a function in Python. Let’s now create individual functions for each case.

——————————————

  def monday(self):
        return “Monday”
  def tuesday(self):
        return “Tuesday”
   def wednesday(self):
        return “Wednesday”
   def thursday(self):
        return “Thursday”
 def friday(self):
        return “Friday”
 def saturday(self):
        return “Saturday”
 def sunday(self):
        return “Sunday”

——————————————

The complete code will look as follows:

——————————————

class PythonSwitch:
def day(self,DayOfWeek):
        default = “Incorrect Day”
        return getattr(self, ‘case_’ + str(DayOfWeek), lambda: default)()
def monday(self):
       
       return “Monday”
 
 def tuesday(self):
        return “Tuesday”
  
 def wednesday(self):
        return “Wednesday”
   
def thursday(self):
        return “Thursday”

 def friday(self):
        return “Friday”
 
def saturday(self):
        return “Saturday”
 
def sunday(self):
        return “Sunday”
my_switch = PythonSwitch()
print (my_switch.day(1))
print (my_switch.day(6))

——————————————

The above code prints the following output

——————————————

Monday

Saturday 

——————————————

Limitations of switch statements

1. There is no provision in the switch, as well as in the case to use float constant.

2. Variable expression can not be used in the case.

3. The use of the same constant in two different cases is not allowed.

4. The relational expression can not be used in the case.

Conclusion

This article taught you what switch-case statements are, what the alternatives can be used in place of switch-case statements, and how they can be used.

During the journey of this article, we came to know that Python doesn’t provide an in-built switch case statement, but these alternatives can be used to make code clean, and better performance can be achieved.

As explained above, Python does not have the facility of an in-built switch case function, but to make code look neat and clean and to get better performance, you can use these alternatives.

With this article, we have tried our best to give the best knowledge about switch-case statements as maximum as possible. Please feel free to share and provide your valuable feedback about this article in the comments below.



Source link

By GIL