×

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 get current date in python?

How to get current date in python? In Python programming language, date and time are not just a data form, but it is possible to import a method called datetime to operate...

3 minutes read.

Python String count() method

Python String count() method The string.count() method returns the number of times a specified value appears in the string. Syntax string.count(sub[, start[, end]]) Parameter sub: This parameter represents a substring to be searched. start: This parameter...

1 minute read.

Class and Static Methods in Python

The method is an important concept to learn for every programmer or data analyst. We know that in OOP's concept, each object has its attributes and behaviors defined through methods....

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.

Best books for NLP with Python

NLP NLP – Natural language processing Computers were created to make the life of mankind easier. But computers cannot understand human language. Instead, they interact with numbers to perform the tasks allotted...

12 minutes read.

Python Packages

A package is a collection of Python modules that share a similar namespace and are generated by putting all of the modules in a single directory with certain special files...

6 minutes read.

Drop() Function in Python

Drop() Function: The python programming language consists of various libraries; some of them are pandas and matplotlib. Data scientists mainly use the pandas library to analyze the data more easily and...

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.

Find Median of List in Python

The median is an enlightening measurement that is utilized as a proportion of the focal inclination of a circulation. It is equivalent to the centre worth of the conveyance. There...

3 minutes read.

Python Image Processing

What is an Image? Images are the pictures that will define the world, and it has their own story, and consists of information about them and these are useful in many...

9 minutes read.

Google Python Class

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.

Unit Testing in Python

The process of testing whether a particular unit is working properly or not is called “UNIT TESTING”. A unit test will check small components in your application. The first and...

7 minutes read.

Hog Descriptor Opencv Python

Python programming language: 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...

3 minutes read.

Python String islower() method

Python String islower() method The string.islower() method returns a boolean value true if all cased characters in the string are lowercase and for  any other value is returns false otherwise. Syntax string.islower() Parameter NA Return This...

1 minute read.

Is Python Case Sensitive

Case sensitivity is the mode of dealing with the written alphabet. The cases of the alphabet are examined and based on these words are being treated. The uppercase and lowercase...

3 minutes read.

Python Super function

The super function is used to access and call the methods or functions involved in the parent class during Inheritance. What is Inheritance? The process where the parent class inherits some of...

3 minutes read.

Python for loop

 Python for loop A for loop in Python executes a block of code for a specified number of times, based on a given sequence. The for loop in Python is different than any other...

3 minutes read.

Map Syntax in Python

Introduction: In Python, a function called map acts as an iterator, returning a result after each item in an iterable has been subjected to a function (tuple, lists, etc.). When you...

6 minutes read.

Python program to convert Celsius into Fahrenheit

Python program to convert Celsius into Fahrenheit This program explains how we can take the temperature in Celsius and convert them into Fahrenheit. Celsius Celsius, also known as centigrade, is a measurement unit...

1 minute read.

Python Control Flow Statements

This article aims to introduce you to what control flow statements are in general and Control Flow Statements in Python programming Language, the Importance of control flow statements and look...

3 minutes read.