×

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 Call Function

In this article, you will learn about calling a function in Python. But before learning this, we should know about functions in Python.So, let’s get some overview of functions in...

6 minutes read.

Python Percentage Sign

In Python, the percentage sign significantly completes two things. They are: It goes about as a Modulo administrator. It helps in string organizing. Allow us to see every one of them plainly. Modulo operator: Like...

2 minutes read.

Python Decorator

Python Decorator: A Decorator is an interesting feature of Python that helps the user design patterns and insert a new functionality to an existing object without making any modifications in...

6 minutes read.

Add in Dictionary Python

Dictionary in python: Dictionaries are a useful data configuration for storing information in Python because they can mimic real-world data arrangements where a particular value exists for a particular key. The...

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

XXhash Python Examples

XXhash Python: xxHash is an extremely rapid hash calculation that operates inside the confines of RAM. Code is incredibly convenient, and hashes (almost nothing/large endian) are same at all levels. Execution of...

4 minutes read.

Flutter Python

The flutter is a frame work available in the python programming language, to create web applications, mobile apps. The flutter is generally used for the development of the backend of...

3 minutes read.

Python program to check whether a given number is prime or not

Python program to check whether a given number is prime or not A positive integer greater than 1 is called a prime number if it is divisible by one and number...

1 minute read.

Python Set intersection() method

Python Set intersection() method The set.intersection() method in Python returns a new set with elements that are similar between two or more sets. Syntax set.intersection(set1, set2 ... etc) Parameter set1- This parameter represents the set to search for...

2 minutes read.

Difference between Package and Module in Python

What are Python modules? A file with the “.py” suffix that includes Python or C executable code is known as a module. Multiple Python commands and expressions make compose a module....

3 minutes read.

Sentence to python vector

Conversion of a Sentence to Vector in Python Before starting the tutorial, let’s just recap about the vector and the respective package that has to be imported in Python. Python Vector: Putting simply,...

3 minutes read.

Python Set intersection_update() method

Python Set intersection_update() method The set.intersection_update() method in Python removes the items that is not present in both sets. It is different from the set.intersection() method, because the intersection()method returns a new set, with only  the common elements...

2 minutes read.

Python Infinity

Introduction We will discover how to define an infinite number in Python in this tutorial. Infinity, as we all know, is a value that cannot be defined and can either be...

5 minutes read.

Python Operators

Operators in Python programming An operator is a symbol that operates on one or more operands. An operand is a value or a variable on which we perform the operation....

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

Returning Multiple Values in Python

Python is considered a general-purpose programming language; it is a high-level programming language that is not much difficult and easier to learn. It is rich in libraries that can be...

3 minutes read.

BOTTLE Python Web Framework

The Bottle is a lightweight WSGI micro web framework for python. It acts like a thin wrapper around a web server where it is distributed as a single file module...

4 minutes read.

Character Set in Python

A collection of legal characters that will recognize by a programming language known as a Character set. Taking python programming language as an instance. The set of characters supported by the...

6 minutes read.

How to run a Program in Python

How to run a Program in Python Writing a program in Python is an easy task, beginners who are ready to kickstart their career in the world of programming can create...

3 minutes read.

List Comprehension in Python

Sometimes we need new lists that are completely based on previously existing lists, so to perform this operation successfully, some of the programming languages come with a syntactic construct known...

5 minutes read.