What’s New ?

The Top 10 favtutor Features You Might Have Overlooked

Read More

3 Ways to Implement Python Switch Case Statement

  • Feb 05, 2021
  • 5 Minute Read
3 Ways to Implement Python Switch Case Statement

In this article, we will learn what is the switch case statement and its requirements. We will also learn whether python language has a switch case statement or not and if yes then how to apply it. Further, we will learn 3 different methods to implement the python switch case statement, along with complete syntax. So, let’s get started!

What is a Switch statement?

In computer programming, a switch case statement is a kind of selection control system used to allow the value of the variable to change the control flow of program execution. The switch case statement is similar to the ‘if’ statement in any programming language. The switch case statement is a replacement of the ‘if..else’ statement in any program. The advantages of using the Switch Case Statement in the program are as given below:

  1. It is easier to debug.
  2. It is easier to read the program by anyone except the programmer.
  3. It is easier to understand and also easier to maintain.
  4. It is easier to verify all values that are to be checked are handled.

So, in short, the switch statement allows us to execute one code block among many alternatives in the program.

Switch Statement in C++/Java

Before moving towards learning the switch case statement in python language and different ways to implement it let us first understand the switch case statement in C++ language. In the switch case statement, the variable is compared to the list of values. This value is known as case and the variable keeps on checking the value until it becomes the same. 

The syntax for switch case statement in C++ is as given:

switch(expression) {
   case constant-expression  :
      statement(s);
      break; //optional
   case constant-expression  :
      statement(s);
      break; //optional
  
   // multiple number of case statement is allowed 
   default : //Optional
      statement(s);
}

Explanation of code: 

  • Expression: It should be an integral type or enumerated type.
  • Constant expression: The constant expression should have the same data type as the variable to be compared with and also it must be literal or constant.
  • Break: The break statement is used to terminate the switch statement if the case value matches the variable value. After the break statement, the flow control of the program jumps to the next line of code immediately after the switch case statement.
  • Default: The default case is used in a switch statement for the situation where no case is executed. Declaring the default case is optional.                                                                                                   

Example:

#include 
using namespace std;
 
int main () {
  
   int marks = '10';

   switch(grade) {
      case '5' :
         cout << "You scored 5 marks" << endl; 
         break;
      case '7' :
      case '7' :
         cout << "You scored 7 marks" << endl;
         break;
      case 'D' :
         cout << "You scored 10 marks" << endl;
         break;
      default :
         cout << "You scored 0 marks" << endl;
   }
   cout << "Your marks is " << marks << endl;
 
   return 0;
}

Output:

 You scored 10 marks

 Your marks are 10

Is there any python switch statement?

It is usually found that the use of switch statements is very rare while programming in the python language. So, always a question arises whether the python language supports the switch case statements or not? Well, the answer to this question is NO. Unlike any other programming language, python language does not have switch statement functionality. This is also a trick question for students to get in their python assignments. So, we use the other alternatives which can replace the switch case statement functionality and make the programming easier and faster. Let us study each python switch statement one by one below.

How to implement Switch Case in Python?

As we studied that the python language does not use a switch case statement like other languages, we can use 3 different replacements to implement a python switch case with syntax.

  1. If-elif-else
  2. Dictionary Mapping
  3. Using classes

Let us understand each python switch syntax one-by-one in detail below:

Method 1) If-elif-else

If-elif is the shortcut for the if-else chain. We can use the if-elif statement and add the else statement at the end which is performed if none of the above if-elif statement is true.

Python Switch Syntax with If-elif-else:

if (condition):
    statement
elif (condition):
    statement
.
.
else:
    statement

Example:

# if-elif statement example 

fruit = 'Banana'

if fruit == 'Mango': 
    print("letter is Mango") 

elif fruit == "Grapes": 
    print("letter is Grapes") 

elif fruit == "Banana": 
    print("fruit is Banana") 

else: 
    print("fruit isn't Banana, Mango or Grapes") 

The output of the above code will be as given below:

 fruit is Banana

Method 2) Dictionary Mapping

If you know the basic python language then you must be familiar with a dictionary and its pattern of storing a group of objects in memory using key-value pairs. So, when we use the dictionary to replace the Switch case statement, the key value of the dictionary data type works as cases in a switch statement.

Example:

# Implement Python Switch Case Statement using Dictionary

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 = {
    1: monday,
    2: tuesday,
    3: wednesday,
    4: thursday,
    5: friday,
    6: saturday,
    7: sunday
    }

def switch(dayOfWeek):
    return switcher.get(dayOfWeek, default)()

print(switch(3))
print(switch(5))

The output of the above code is as given below:

 wednesday

 friday

Method 3) Using classes

Along with the above methods to implement the switch case in python language, we can also use python classes to implement the switch case statement. An object constructor that has properties and methods is called a class. So, let us see the example of performing a switch case using class by creating a switch method inside the python switch class.

Example:

class PythonSwitch:
    def day(self, dayOfWeek):

        default = "Incorrect day"

        return getattr(self, 'case_' + str(dayOfWeek), lambda: default)()

    def case_1(self):
        return "monday"

 

    def case_2(self):
        return "tuesday"

 

    def case_3(self):
        return "wednesday"

   

    def case_4(self):
       return "thursday"

 

    def case_5(self):
        return "friday"

 

    def case_7(self):
        return "saturday"
    
    def case_6(self):
        return "sunday"

   
my_switch = PythonSwitch()

print (my_switch.day(1))

print (my_switch.day(3))

The output of the above code is as given below:

 monday

 wednesday

Now you know 3 switch case program in python.

Conclusion

In this blog, we studied what is switch case and its implementation in python language using 3 ways as python does not have the functionality to use a switch statement, unlike other languages. Now you also code for python switch case to try it yourself. Therefore, it is highly recommended to use a python switch statement while programming because it increases the coding efficiency and easier to implement.

FavTutor - 24x7 Live Coding Help from Expert Tutors!

About The Author
Shivali Bhadaniya
I'm Shivali Bhadaniya, a computer engineer student and technical content writer, very enthusiastic to learn and explore new technologies and looking towards great opportunities. It is amazing for me to share my knowledge through my content to help curious minds.