Python switch case statement examples [Beginners]

Introduction to Python switch statement

Switch cases are one of the important and powerful techniques that programmers and developers use to control the flow of a program. It is the best replacement for long if-else statements. Switch cases provide a cleaner and faster way to control the flow of the program.

Python does not have a switch case construct over the self, as other programming languages like C++ and java do. Python uses other constructs like lambda, dictionary and classes to write switch case statements. In this tutorial, we will learn about the python switch statement, its syntax along with examples. Moreover, we will also cover different ways to implement switch statements in Python.

Advertisement

 

Getting start with Python switch statement

When we define switch statements in any programming language, it follows a general pattern of implementation. It works by evaluating the switch statement, compares the result of the evaluation with the values defined in each of the case blocks, and tries to find the matches. If it finds a match, then the code inside the case block will be executed and the values are returned. In this section, we will see the basic syntax and usage of a switch statement in Python.

 

Syntax of Python switch statement

Python does not have a specific syntax for a switch statement. It can be implemented in a number of different ways. But in general, in any programming language, the syntax of a switch statement looks like this.

# Python switch statement syntax
switch(arg)
{
   case 1: statement if arg = 1;
       break;
   case 2: Statement if arg = 2;
       break;
   .
   .
   .
   case n: statement if arg = n;
       break;
   default # if arg doesn't match any
}

You can see that there is a break statement after each case. It is because we don't want to check other cases if we already found the correct one. If we will not specify the break statement, then even if our switch argument matches with case 1, it still will check all cases. So to avoid this checking, even after finding the match, we use a break statement. The last statement is the default, which will be executed if no match is found.

 

Different ways to implement python switch statement

Unfortunately, Python does not support the conventional switch case statements as other languages provide. But that does not mean python does not support switch statements. In Python, there are several ways or replacements that can be used in the place of traditional switch statements, which are much easier than the traditional ones. In this section, we will see some different ways to implement a python switch statement.

 

Python switch statement using if-elif ladder

If-else ladder in python can be an alternative to Python switch case statements. We can add a chain of if elif statements that will work as a switch. See the below syntax of how a if elif statement can be used as a python switch statement.

# creating a function for switch statement
def switch(case):

   # checks if the argument matches first case
   if case == case1:
       # return statement
   # checks if the argument matches second case
   elif case == case2:
       # return statement
   .
   .
   .
   # else statement
   else:
       # return statement
switch(case)

Else statement in the above example works as default one in switch, it will be executed if none of the above cases are true.

Advertisement

Now let us take two practical examples and see how if-elif can work as a Python switch statement. See the example below, which returns the name of the day depending on the input.

# creating a function for switch statement
def switch(case):

   # checks if the argument matches first case
   if case == 1:
       print("Monday")

   # checks if the argument matches second case
   elif case == 2:
       print("Tuesday")

   # checks if the argument matches third case
   elif case == 3:
       print("Wednesday")

   # checks if the argument matches fourth case
   elif case == 4:
       print("Thursday") 

   # checks if the argument matches fifth case
   elif case == 5:
       print("Friday") 

   # checks if the argument matches sixth case
   elif case == 6:
       print("Saturday")    

   # checks if the argument matches seventh case
   elif case == 7:
       print("Sunday") 

   else:
       print("Please enter number between 1-7")

# calling function
switch(4)
switch(9)

Output:

Thursday
Please enter number between 1-7

The elif statement is working as a switch with a break statement. We can use if statement instead of elif as well, but it will be like a switch statement without a break statement. The else statement is working as a default statement in switch.

Let us take one more example.

# creating a function for switch statement
def switch(case):
   number1 = 8
   number2 = 4

   # checks if the argument matches first case
   if case == "+":

       # prints the sum of two numbers
       print("sum is {}".format(number1+number2))

   # checks if the argument matches second case
   elif case == "-":

       # prints the subtraction of two numbers
       print("Subtraction is {}".format(number1-number2))

   # checks if the argument matches third case
   elif case == "/":

       # prints the division of two numbers
       print("division is {}".format(number1/number2))

   # checks if the argument matches fourth case
   elif case == "*":

       # prints the product of two numbers
       print("sum is {}".format(number1*number2))

   # else statement
   else:

       # print the invalidation
       print("Please provide valid symbol!")

# calling function
switch("+")
switch("/")

Output:

sum is 12
division is 2.0

 

Python switch statement using class

We know that classes and objects are used in Python object-oriented programming. It is also possible to use classes to implement switch cases in Python and they are easy to implement as well.

Following is the simple syntax of a python switch statement using a class.

# Implement Python Switch Case Statement using Class
class Switch:

   # creating constructor for switch
   def switch(self, dayOfWeek):

       # constructor statements

   # method for case one
   def case_1(self):

       # return if case 1 satisfied

   # method for case two
   def case_2(self):

       # return if case 2 satisfied
   .
   .
   .
   # Method for case n
   def case_n(self):

       # return if case n is satisfied

# creating object
switchObject = Switch()

Now let us solve a couple of examples using class as a python switch statement. We will take the same example of days in the week through a class.

Advertisement
# Implement Python Switch Case Statement using Class
class Switch:

   # constructor
   def switch(self, day):

       # creating a default statement
       def default():
           print("Please enter value between 1-7")

       # using getattr method
       return getattr(self, 'case_' + str(day), lambda: default())()

   # case 1
   def case_1(self):

       # print monday
       print("Monday")

   # case 2
   def case_2(self):

       # print tuesday
       print("Tuesday")

   # case 3
   def case_3(self):

       # print wednesday
       print("Wednesday")

   # case 4
   def case_4(self):

       # print thursday
       print("Thursday")

   # case 5
   def case_5(self):

       # print friday
       print("Friday")

   # case 6
   def case_6(self):

       # print saturday
       print("Saturday")

   # case 7
   def case_7(self):

       # print sunday
       print("Sunday") 

 # creating object
switchObject = Switch()

# calling the created object
switchObject.switch(1)
switchObject.switch(6)
switchObject.switch(10)

Output:

Monday
Saturday
Please enter value between 1-7

​Now let us try to understand how the above example works: We will go through the above code step by step:

  • First, we created a Switch class that defines  switch() method:
  • Inside the switch() method, we create a default method in case we couldn’t match the argument with any of the cases.
  • The switch() method takes the day of the week as an argument, then converts it to string and appends it to the case_ literal. After that, the resultant string gets passed to the getattr() method.
  • getattr() method is used to access the attribute value of an object and also give an option of executing the default value in case of unavailability of the key.
  • If the string does not match, then the getattr() returns the lambda function as default.
  • The class also has the definition for each of the functions specified to different cases.

Let us take one more example of a python switch statement using class.

# Implement Python Switch Case Statement using Class
class Switch:

   # constructor
   def switch(self, symbol, num1, num2):

       # creating a default statement
       def default():
           print("Please enter valid value")

       # using getattr method
       return getattr(self, str(symbol), lambda: default())(num1, num2)

   # case 1
   def add(self, num1, num2):

       # print sum
       print(num1+num2) 

   # case 2
   def subtract(self, num1, num2):

       # print subtraction
       print(num1-num2)

   # case 3
   def multiply(self, num1, num2):

       # print multiplication
       print(num1*num2)

   # case 4
   def divide(self, num1, num2):

       # print division
       print(num1/num2)

# creating object
switchObject = Switch()

# calling the created object
switchObject.switch("add", 2, 4)
switchObject.switch("divide", 9, 3)

Output:

6
3.0

 

Python switch statement using dictionary mapping

We know that python dictionaries are key-value pairs that are widely used for a number of purposes. We can use dictionaries to implement a  Python switch statement. Here is a simple python switch statement syntax using dictionary mapping.

# creating function which contains dictionary
def switch_function(args):

  # dictionary containing key:value
  switcher = {

      # case 1
      key1: value1

      # case 2
      key2: value2
      .
      .
      .
      # case n
      keyn:valuen
  }

  # return default
  return default value

Now let us take the same example of days of the week and implement using dictionary mapping.

# function containing dictionary
def switch_function(num):

  # dictionary
  switcher = {

      # case 1
      1: "monday",

      # case 2
      2: "Tuesday",

      # case 3
      3: "Wednesday",

      # case 4
      4: "Thursday",

      # case 5
      5: "friday",

      # case 6
      6: "Saturday",

      # case 7
      7 : "sunday"
  }

  # get the value of dictionary using key
  # if not found, return message
  return switcher.get(num, "Please enter number between 1-7")

# calling function
print(switch_function(4))
print(switch_function(10))

Output:

Thursday
Please enter number between 1-7

 

Summary

A Python switch statement works by evaluating a switch statement and comparing the result of that statement with values in a case statement. If a match is found, the respective block of code is run, else the default block runs. Although python does not have switch statements by itself, there are many ways to implement the same logic through various methods. In this tutorial, we learned everything about a python switch statement, different syntax, and few methods to implement python switch statements by taking practical examples.

Advertisement

 

Further Reading Section

Python switch statement
More control follow tools
Switch case statement

 

Didn't find what you were looking for? Perform a quick search across GoLinuxCloud

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can either use the comments section or contact me form.

Thank You for your support!!

Leave a Comment