Switch Case Replacement in Python

by | Jan 10, 2023 | Python

Home » Python » Switch Case Replacement in Python

Switch Case in Python

Switch Case is a very popular concept that a lot of programmers use as a conditional operation. Most common languages like C/ C++, and Java, among others, have a switch statement. However, in Python, the switch case statement is not available. Therefore, in this article, we will try to create our switch case statement with the help of dictionary mappings.

Sample Program that will convert a given number into a string according to a condition

#We will be creating a switch statement with the help of dictionary mappings here.

def numbers_to_Strings (argument):
switcher = {
0: “zero”,
1: “one”,
2: “two”,
}

 

#The get() method of the dictionary data type will return the value of the argument that is passed to #the method. If the value is not available in the dictionary, the second argument passed to the #method will be assigned as the value of the first argument by default.

#Main Driver function
if _name_ == “_main_”:
argument = 0
print (numbers_to_Strings (argument))

Switch Case in C++

If the code above is converted to a language that allows switch statements like C++, it will give the same result as the code below:

//Code in C++ implementing the same Switch case as above in the Python program.
#include <bits/stdc++.h>
using namespace std;
//function that will use switch case to choose and convert a number to string
string numbers_to_Strings (int argument)
{
switch (argument)
{
case 0:
return “zero”;
case 1:
return “one”;
case 2:
return “two”;
case 3:
return “nothing”;
};
};
//main driver fuction
int main ()
{
int argument = 0;
cout << numbers_to_Strings (argument);
return 0;
}

 

OUTPUT
Zero

 

Author

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Author