×

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

Python Struct

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....

3 minutes read.

Python zip() Function

Python zip() Function The zip() function makes an iterator that aggregates elements from each of the iterables and returns an iterator of tuples. Syntax zip(*iterables) Parameter iterables: Iterator objects that will be joined together Return This function...

1 minute read.

Text detection using Tkinter in Python

Tkinter: The standard Python technique for building Graphical User Interfaces (GUIs) is Tkinter, which is included in all popular Python distributions. The only framework included in the Python standard library is...

4 minutes read.

Python Set symmetric_difference() method

Python Set symmetric_difference() method The set.symmetric_difference() method returns a new set, which is the symmetric difference of two sets. The returned set contains only the unique items and, hence, deleting the common elements of...

2 minutes read.

Executing Shell Commands in Python

This tutorial aims to make us understand what a Shell is, what is the importance of a Shell, what are Shell commands in Python, and how can we execute the...

3 minutes read.

Check Letter in a String Python

Checking a specific letter or a character in a given string or a string which is taken as an input from the user is possible in Python in broadly three...

3 minutes read.

Python Set issuperset() method

Python Set issuperset() method The set.issuperset() method in Python returns a boolean value True if all items in the specified set exists in the original set, else it returns False. Syntax set.issuperset (set1) Parameter set- This parameter represents the...

2 minutes read.

Python Web Development projects

What is Python? Python is currently one of the most widely used computer programming languages. This isn't just an exaggeration; Python is the second-most famous programming language on the software development...

3 minutes read.

Expressions in Python

What is Expression in Python? The expression contains more than one operator as well as the operands with it. Expression helps us to produce some other values. In the Python programming...

12 minutes read.

What is the re.sub() function in Python

There. sub () function is used to return a string by replacing the occurrences of a specific character or pattern with a replacement string. To use this function, import the...

3 minutes read.

Python Dictionary clear() method

Python Dictionary clear() method The dictionary.clear() method in Python removes all the elements from a dictionary. Syntax dictionary.clear() Parameter NA Return None Example 1 # Python program explaining # the dictionary.clear() method # initialising the dictionary fruits =...

1 minute read.

Iterate through the list in Python

One of the six basic data types of the Python computer language is the list. You must be familiar with the methods and functions that deal with lists in order...

7 minutes read.

Cube Root in Python

In general, the cube is a three-dimensional solid figure that has 6 square faces. It is also called a geometrical shape with six equal faces, eight vertices, and twelve edges....

3 minutes read.

Python Bubble Sort

Bubble sort is one of the techniques used to sort the elements in lists in a certain order, either in ascending or descending order. It is called Bubble sort because...

4 minutes read.

Python String Lowercase

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....

3 minutes read.

How to run Python program in CMD

How to run python program in cmd Command Prompt provides us all together with a different approach for dealing with our programs. The programs can be executed by accessing the directories. In...

3 minutes read.

Conditional Expressions in Python

In Python conditional expression are sometimes referred to operator called as ternary operator. Not only Python supports ternary operator but many other programming languages supports it. Ternary operator are the...

2 minutes read.

How to plot multiple linear regression in Python

This article lets us look into linear regression in Python and how we can plot multiple linear regressions in it. Linear regression One of the simplest and most widely used Machine Learning...

4 minutes read.

Import Module in Python

In this article, you will learn everything about “ Import ” in Python. Modules in python that are already created can be accessed and used in another code by importing the...

6 minutes read.

Python try except

Before diving right into loads of syntax we need to know what does try except is used for and how it helps users in writing programs What is Python try except? Python...

5 minutes read.