The Wayback Machine - http://web.archive.org/web/20220521185454/https://www.geeksforgeeks.org/switch-case-in-python-replacement/
Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Switch Case in Python (Replacement)

  • Difficulty Level : Easy
  • Last Updated : 12 Apr, 2022

What is the replacement of Switch Case in Python?

Unlike every other programming language we have used before, Python does not have a switch or case statement. To get around this fact, we use dictionary mapping.

Python3




# Function to convert number into string
# Switcher is dictionary data type here
def numbers_to_strings(argument):
    switcher = {
        0: "zero",
        1: "one",
        2: "two",
    }
 
    # get() method of dictionary data type returns
    # value of passed argument if it is present
    # in dictionary otherwise second argument will
    # be assigned as default value of passed argument
    return switcher.get(argument, "nothing")
 
# Driver program
if __name__ == "__main__":
    argument=0
    print (numbers_to_strings(argument))

This code is analogous to the given code in C++ : 

CPP




#include<bits/stdc++.h>
using namespace std;
 
// Function to convert number into string
string numbers_to_strings(int argument){
    switch(argument) {
        case 0:
            return "zero";
        case 1:
            return "one";
        case 2:
            return "two";
        default:
            return "nothing";
    };
};
 
// Driver program
int main()
{
    int argument = 0;
    cout << numbers_to_strings(argument);
    return 0;
}

Output: 

Zero

But In Python 3.10 and after that, Python will support it’s:

This it’s my example code:

Python3




def number_to_string(agrument):
    match agrument:
        case 0:
            return "zero"
        case 1:
            return "one"
        case 2:
            return "two"
        case default:
            return "something"
 
 
if __name__ = "__main__":
    agrument = 0
    number_to_string(agrument)

It’s like all code above it’s

This article is contributed by Shashank Mishra (Gullu). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
 


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!