Switch Statement in Python (Not Supportable)

Unlike other programming languages like C/C++/Java, Python does not have any dedicated switch case statement.

A switch statement is a multiway decision statement that executes a statement by comparing the value of a variable to the values specified in the case statements.

If it matches, a statement or a block of statements associated with that case is executed.

For example, the following Java switch statement prints the name of city depending on the city value. Mumbai will display when the value is m; Dhanbad will display when the value is d; and so on.

If city value does not match with the specified values: m, d, c, or r, then none of the statements will execute. In this case, the default statement will execute and it will display no city. Look at the following program code below.

public class SwitchTest {
public static void main(String[ ] args) 
   char city = 'd'; // Here, city is set to 'd'.
// Switch expression with char value.
   switch(city) {
// Case statements.
   case 'm':
   case 'd':
   case 'c':
   case 'r':

// Default case statement.
   System.out.println("No city");

Python has no such switch case structure because it does not have any switch keyword. However, Python programming language provides lots of features that can make switch functionality possible in a cleaner way. They are as:

  • Using if-elif-else statements
  • Using Dictionary mapping
  • Python class
  • Using Python Functions and Lambdas
  • Using structural pattern matching

Let’s understand each method one by one with the help of examples.

Implementing Switch Statement in Python using if-elif-else

The if-elif-else statement is a way to implement a switch case statement in Python. If the specified condition is true, then a statement or block of statements will execute.

If false, the block of statements will not execute. Else block statement will execute if none of the above conditions meet.

Let us write the code to implement switch statement in Python using if-elif-else statements. We will take the above example program.

Program code:

city = 'd' # Initialize the variable.
if city == 'm':
elif city == 'd':
elif city == 'c':
elif city == 'r':
    print('No city')

Implementing Switch Statement in Python using Dictionary

Some Python programmer uses the concept of dictionary mapping instead of using if-elif-else statements.

A dictionary in Python is an unordered collection of data values. It stores the collection of data values as key-value pairs. Keys in the dictionary mapping should be unique because values in the dictionary are indexed by keys.

We can use the get() method the value for a given key. If the key is not available, then it returns the default value. To implement the switch statement, the key-value pair of dictionary data type works like a ‘case’ in a switch case statement.

Let’s write the program code in Python to implement the switch case statement using dictionary mapping.

Program code:

# Implementing switch case statement in Python using Dictionary.
def m():
    return "Mumbai"
def d():
    return "Dhanbad"
def c():
    return "Chennai"
def r():
    return "Ranchi"
def default():
    return "No city"

# Creating a dictionary and put these in it.
switcher = {
    1: m,
    2: d,
    3: c,
    4: r,
# Creating a function named switch with a parameter.
def switch(city):
    return switcher.get(city, default)()
print(switch(2)) # Calling function.
print(switch(3)) # Calling function.

In this example, we have created different functions which return the name of city. Then, we have created a dictionary in which we have put these in the form of key-value pairs.

After constructing the dictionary, we created a main function named switch with a parameter. This parameter takes a user input in the form of keys to find the name of city.

When we call these values with the help of keys, the specific function gets called, and we get the desired output on the console. At the last, we have called functions by passing two key arguments and printed the desired output.

Let’s write a program in Python to construct a simple calculator by implementing switch statement using dictionary mapping.

Program code:

# Program to create a simple calculator by implementing switch case statement in Python using Dictionary.
x = int(input('Enter your first number: '))
y = int(input('Enter your second number: '))
choice = int(input('Enter your choice 1: addition 2: subtraction 3: Multiplication and 4: division: '))
def addition():
    sum = x + y
    return sum
def subtraction():
    sub = x - y
    return sub
def multiplication():
    multiply = x * y
    return multiply
def division():
    div = x / y
    return div
def default():
    return "You are not entered the valid choice."

# Putting these in the dictionary.
switcher = {
    1: addition,
    2: subtraction,
    3: multiplication,
    4: division,
def switch(number):
    return switcher.get(number, default)()
      Enter your first number: 20
      Enter your second number: 30
      Enter your choice 1: addition 2: subtraction 3: Multiplication and 4: division: 3

Implementing Switch Statement using Python Class

In this method, we are going to use Python class to implement switch case statement.

In Python, a class is an object constructor that contains properties and methods. Let’s take an example and how can we implement switch cases using classes?

In this example, we will use a getattr function that returns the name of the attributes present in the object as output. If the object’s attribute is not present, we will get a default value.

The general syntax of this function is as below:

getattr(object, name, default)

This function takes three parameters: object, name, and default. Read the explanation of these parameters below.

  • object: It represents an object name whose attribute is to be returned. It is a mandatory parameter.
  • name: It is a string that contains the object’s attribute name. It is also a mandatory parameter.
  • default: It returns the default statement if the attribute is not present in the object.

Program code:

# Creating a class.
class PythonSwitch():
    def main_function(self, name_of_day):
        default = "Incorrect name of day"
        method_name = 'day_' + str(name_of_day)
        method = getattr(self, method_name, lambda: default())
        return method()

    def day_1(self):
        return "Sunday"
    def day_2(self):
        return "Monday"
    def day_3(self):
        return "Tuesday"

    def day_4(self):
        return "Wednesday"
    def day_5(self):
        return "Thursday"
    def day_6(self):
        return "Friday"
    def day_7(self):
        return "Saturday"

# Creating an object of class.
my_switch = PythonSwitch()
print(my_switch.main_function(1)) # Calling function with passing argument value.
print(my_switch.main_function(3)) # Calling function.

If you are unable to understand the above coding, you don’t worry. When you will learn about the class in Python, then you will easily understand the whole code.

Implementing Switch Case using Functions and Lambdas

In this method, we can use functions and lambdas to implement switch case statement in Python.

A lambda function is a small anonymous function that can take n numbers of parameters but only has a single expression. The basic syntax to define a lambda function is as:

lambda parameters: expression

In the above syntax, lambda is a keyword that is used to create a lambda function. Then, we will have to pass parameters and expressions to it with a colon (:) separating them. For example:

x = lambda number: number * 20

In the preceding example, we have defined a lambda function that takes a parameter and returns a single expression. The expression returns the number by multiplying it by 20.

We have stored the returned result in the variable x. Then, we have printed the value of variable x when we passed a value 4 to it. At the end, we got the desired output on the console.

Let’s move to the example and see how to implement switch case statement in the program using dictionary with the help of lambda function.

Program code:

def a():
    return 'Apple'
def m():
    return 'Mango'
def o():
    return 'Orange'
def fruits(i):
    switcher = {
        1: a,
        2: m,
        3: o,
        4: lambda: 'Banana'
    funct = switcher.get(i, lambda: 'Invalid')
    return funct()
print(fruits(3)) # Calling function.
print(fruits(0)) # Calling function.

In this example, we have created different functions which return the name of fruits. Then, we have created the main function named fruits() with parameter i.

In this function, we have created a dictionary in which we stored different key-value pairs. When we will call these values with the help of keys, a specific function gets called, and we get the desired output.

Inside the Dictionary, we have used the anonymous lambda function which is considered as values in dictionaries.

Implement Switch Statement with match and case in Python 3.10

Until the Python 3.10 version, Python introduced no feature like what switch statement does in other programming languages.

Hence, if you have needed to execute multiple conditional statements in any program, you would’ve had to use the if-elif-else statements as we used in the above program.

From Python 3.10 version onwards, we can implement switch case feature called “structural pattern matching” with the help of match and case keywords.

The general syntax for a match statement to write switch statements having the structural pattern matching feature is as below:

match expression:
    case pattern-1:
    case pattern-2:
    case pattern-3:
    case _:

In the above syntax, expression can be any valid Python expression. pattern-1, pattern-2, . . . represents an actual matching pattern that is new in Python. Inside the case block, we can have multiple statements. The underscore symbol (_) acts as a wildcard that is used to define a default statement.

An example code for implementing switch statement written with match and case keywords is as below:

Program code:

# This program code will execute only in python 3.10 or above versions
lang = input('Which programming language do you want to learn? ')

match lang:
    case "JavaScript":
        print('You will be a web developer after learning JavaScript.')

    case "Python":
        print("You will be a Data Scientist after learning Python.")

    case "PHP":
        print("You will be a backend developer after learning PHP.")

    case "Solidity":
        print("You will be a Blockchain developer after learning Solidity.")

    case "Java":
        print("You will be a software developer after learning Java")
    case _:
        print("Language does not matter.")
      Which programming language do you want to learn? Python
      You will be a Data Scientist after learning Python.

In this example, we have created a variable named lang that stores entered programming language. Then, we create a match structure. The value of variable lang is compared with each case until it matches one.

Once a match is found, the case’s pattern is executed. After matching case pattern one, Python will not check the value against additional patterns.

Since the user entered Python as input, the message has displayed ‘You will be a Data Scientist after learning Python’ on the console.

Match structure can be of different types, including string or integer. Let’s take one more simple example based on it for the best practice.

Program code:

choice = int(2)
match choice:
    case 1:
        print('You chose 1')
    case 2:
        print('You chose 2')
    case 3:
        print('You chose 3')
    case _:
        print('Default option')
      You chose 2

Thus, implementing switch statement in Python using match structure is similar to that of switch cases in C++, Java, etc. Match structure makes your code cleaner and easily understandable if you are dealing with multiple conditional statements.

In this tutorial, you have learned about how to implement switch statement in Python using various methods. Hope that you will have understood the basic concepts of each implementing method and practiced all example programs.
Thanks for reading!!!