×

Python Switch Case

What is a Switch Case Statement?

In the programming languages, a switch statement is a logical loop or syntax that tests the variable's value and compares it with multiple cases. Once the match is found with the cases given in the function, the block statement which is associated with that particular variable will be executed.

  • Each case in the given switch statement inside the block has a different number or name.
  • The number or name of the case in the switch statement is referred to as the identifier of the case.
  • When a user provides value through input, the switch statement compares this value with all of its cases inside the block.
  • The process of matching the value with the case in the switch statement runs until the match is found.
  • In case when no match is found with the value given by the user, the switch statement will give us a default output.

Note: A switch case statement in any Programming language is a type of selection control which allows the user to let their input variables to change the control flow of the program and execution via searching and mapping.

Python doesn't support the switch case statement:

Although many popular languages like Java, C, C++, PHP, etc., have an in-built switch case statement, it is very surprising to know that the Python language doesn't support the switch statement.

There is no keyword as 'switch' present inside Python programming language.

Switch case replacement in Python (replacement):

In this section, we will write a program in Python, which will act like a switch statement program works in other programming languages.

Since there is no switch statement is available in Python, so we have to use some Pythonic way to implement syntax same as switch statement in our program. For this, we will use some powerful dictionary mappings that are also known as associative arrays. These associative arrays provide simple one-to-one key-value mappings.

Here is an example of a Python program which is the implementation of the switch statement.

Example: In the following example, we will write separate functions, create a dictionary and then and we will build an input function so that the whole Python code will act as a switch statements that work in other programming languages.

We will follow the following steps to build an implementation of the switch case statement:

Step 1: First, we will start by creating separate functions for each case (representing season) that we want to handle.

def spr():
    return ('It is Spring', )
def mer():
    return ('It is Summer', )
def aut():
    return ('It is Autumn', )
def win():
    return ('It is Winter', )
def default():
    return 'Your given input represents an Invalid Season!'

Note: Always make sure that there is a default case also while handling cases.

Step 2: The next step for us is to define the dictionary for the defined function and cases.

switch_case = {
    1: spr,
    2: mer,
    3: aut,
    4: win
    }

Step 3: The last step for us is to create a function that will take input as an integer from the user and run through all the cases we have defined. The integer function value will automatically invoke the corresponding case function after the dictionary hooks up.

def switch_input(x):   
 return switch_case.get(x, default)()

Now the complete Python program ready with switch case implementation will look like the given code:

def spr():
    return ('It is Spring', )
def mer():
    return ('It is Summer', )
def aut():
    return ('It is Autumn', )
def win():
    return ('It is Winter', )
def default():
    return 'Your given input represents an Invalid Season!'
switch_case = {
    1: spr,
    2: mer,
    3: aut,
    4: win
    }
def switch_input(x):   
 return switch_case.get(x, default)()

Now, let's add output variable a in this statement so that the program will give us desirable output. We will give two input let's values to run our program.

print (switch_input(2))
print (switch_input(8))

Now, the final program will look something like this:

def spr():
    return ('It is Spring', )
def mer():
    return ('It is Summer', )
def aut():
    return ('It is Autumn', )
def win():
    return ('It is Winter', )
def default():
    return 'Your given input represents an Invalid Season!'
switch_case = {
    1: spr,
    2: mer,
    3: aut,
    4: win
    }
def switch_input(x):   
 return switch_case.get(x, default)()
print (switch_input(2))
print (switch_input(8))

When we run the program, we will get the following output:

('It is Summer',)
Your given input represents an Invalid Season!

That's how we can implement a program to use it as a switch case statement in Python programming.


Related Topics

How to open a file in python

Opening a File in Python Python is a user-friendly programming language that makes almost every concept easy. It provides many inbuilt functions in its libraries to work with files. Using these...

6 minutes read.

Python String rindex() method

Python String rindex() method The string. rindex() method in Python returns the highest index of the substring inside the string (if found). If the substring is not found, it raises an...

2 minutes read.

Math Module in Python

In this article, you are going to learn everything in detail about the “ math “ module in Python. We can normally work with general operations using python without importing or...

16 minutes read.

Kite Python

Kite in Python: The Kite is a package provided by the python programming language; it works with the help of artificial intelligence and helps us write code inside the visual studio....

3 minutes read.

How to Convert Int to String in Python?

Every value we use or store in a variable in Python will have a specific data type. It describes the value's nature; based on that, Python will automatically assign a...

4 minutes read.

How to check data type in python

The data type represents the nature of a variable; it determines what kind of data it can store and what operations can be carried out on it. There are five...

4 minutes read.

Python Random shuffle( ) method

The shuffle() is used to change the positions of the elements in the mutable sequences. The shuffle( ) function will change the positions of the elements in the sequence of...

3 minutes read.

GUI Calculator in Python

Introduction In Python, we can develop a GUI(Graphical User Interface) with multiple options. It offers us some great and commonly used methods for the development of the Graphical User Interface. Tkinter...

4 minutes read.

How to Print Pattern in Python

How to Print Pattern in Python. Pattern programs are really important for beginners and they are always asked in all the technical interviews. Multiple loops approach is used to print the different...

6 minutes read.

Python Letter to Number

Python Letter to Number In this tutorial, we will convert the given letters into numbers using a Python. We will convert the given letter into the letter value as defined in...

3 minutes read.

Read Text files in Python

In Python, there are many ways to read text files. Before going into the detailed structure of reading a text file, let us understand how reading text files takes place...

4 minutes read.

Global variables in python

In Python, considering the scope, variables are categorized into global and local variables. In this article, we will discuss these two types along with examples. Any variable holds a value in...

4 minutes read.

Python Fit Transform

In machine learning, fit (), transform(), fit transform () methods are provided by scikit learn package. This package is used in model fitting and data processing. These methods are implemented...

2 minutes read.

os.stat() method in Python

In Python, the os module provides the capacity to interact with the operating system. The operating system comes under the Python module. In this module, Python provides a specific feature...

3 minutes read.

How To Take Multiple Inputs In Python

In C language, we make use of the scanf() function to obtain the values from the user and store it in the variable. Coming to the Python language, we use the...

5 minutes read.

Python Loop through a Dictionary

Introduction in this tutorial, we will discuss in python How to Loop Through a Dictionary. In contrast to other Data Types, which can only retain a single value as an element, a Dictionary...

4 minutes read.

Python String isupper() method

Python String isupper() method The String.isupper() method in Python returns a boolean value ‘true’ if all cased characters in the string are uppercase else for any other value is returns false. Syntax String.isupper() Parameter NA Return This...

2 minutes read.

Python Syntax

Python is a strong object-oriented programming language that is simple to learn. Python was created to be a very readable programming language. The syntax of the Python programming language is...

8 minutes read.

Python vs PHP

Python Python is a high-level, object-oriented, interpreted language that is used to create independent program and algorithms for a variety of applications. It has a large library support base. In 1990,...

3 minutes read.

Get Bounding Box Co-ordinates Python

Python: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

6 minutes read.