How to Use Switch Case in Python with User Input[5 ways]

In this Python tutorial, you will learn how to use switch cases in Python with user input in multiple ways and some practical examples based on real-world scenarios.

Generally, we use if-else statements in Python when there are only two possibilities: the user can input only (YES / NO). But what if we give the user more options to input anything?

While working on the Python Project, I needed to take user input as the brand name of the mobile phones they wanted to buy so that I could display all the models of that mobile. For example, If they gave input as Samsung, I would display a list of all models of that brand.

So, I found different ways and approaches that helped me quickly complete this task in Python.

5 Ways to Use Switch Case in Python with User Input

Let’s understand the scenario more clearly with practical examples,

The output should look like this:

Enter the brand name : Samsung

NEW. Galaxy S24 Ultra.

Galaxy Tab S9 Series.
Galaxy Watch6.
NEW. Galaxy A55 5G.

So, we’ve found 5 different ways to take user input like this and display a message based on that input.

Let’s explore every approach individually with their syntax and practical examples.

Switch Case in Python Using Dictionaries

We can use dictionaries as a switch case in Python. When a user gives input to search for anything, the input matches the dictionary key, and if found, it prints the values of that key.

Syntax

dict = {Keys : Values}
  • dict = {Keys: Values}: Here, keys can be anything like string, integer, or float but not other collections like list or tuples. Every key should be unique.

Let’s understand this with the practical example of taking user input and using switch cases in Python.

dict={
    "samsung": ["Samsung S23","Samsung Z Fold 5","Samsung Z Flip 5"],
    'iphone': ['15 Pro Max','15 Pro','SE (2022)'],
    "google": ["Pixel 7", "Pixel 7 Pro", "Pixel 6a"],
    "huawei": ["Huawei P60", "Huawei Mate 50", "Huawei Nova 9"],
    "xiaomi": ["Xiaomi Mi 12", "Redmi Note 12", "Xiaomi 12 Ultra"],
    "oneplus": ["OnePlus 10 Pro", "OnePlus 10R", "OnePlus Nord 3"],
    "oppo": ["Oppo Find X5", "Oppo Reno 8", "Oppo A96"],
    "realme": ["Realme GT 3 Pro", "Realme X4", "Realme C35"]
}

user_input = input("Which company mobile you need: ").lower()

if user_input in dict:
    print(f"List of {user_input} mobiles")
    for i in dict[user_input]:
        print("->",i)

else:
    print("Sorry this brand is not available")
how to use Switch Case in Python Using Dictionaries

In the above code, first, we take the user input as a string because all the dictionary keys are in a string.

READ:  Python - Create Dictionary Of Tuples

The user gave input as “one plus,” so first, it will check whether that brand is available in the dictionary. If yes, then it will print all the models of that brand individually using the for loop in Python.

Switch Case in Python With User Input Using if-elif-else

In programming terms, we can also use if-elif-else, also known as the if-else ladder. Here, we can take user input and check that input with every condition individually.

If the condition is True, it will execute the statement block for that condition. If none of the given conditions are true, it will print the other statement block in Python.

Syntax

if <condition>: 
    # statement block
elif <condition>: 
    # statement block
else <condition>: 
    # statement block
def printMonth(num):
    if num == 1:
        month ='You selected January month'
    elif num == 2:
        month = 'You selected February month'
    elif num == 3:
        month = 'You selected March month'
    elif num == 4:
        month= 'You selected April month'
    elif num == 5:
        month= 'You selected May month'
    elif num == 6:
        month = 'You selected June month'
    elif num == 7:
        month = 'You selected July month'
    elif num == 8:
        month = 'You selected August month'
    elif num == 9:
        month= 'You selected September month'
    elif num == 10:
        month= 'You selected October month'
    elif num == 11:
        month= 'You selected November month'
    elif num == 12:
        month= 'You selected December month'
    else:
        print("Invalid Input...please try again later")
    return month

user_input = int(input("Enter Number of Month : "))

print(printMonth(user_input))
python switch case alternative using if-else ladder in Python

In the above code, first, it will take the user input as an integer and ask the user to “Enter several months: then it will call the printMonth() function by giving user_input as a parameter like this: printMonth(user_input).

READ:  How to check if an object is iterable in Python? [4 Methods]

Then, it will compare every value with the user_input. In the code, the user gave five as an input and got the output “You selected May month.”

Python Switch Case by Calling a Function

Here, we will define a function and return the statement based on the user input to work like a switch case. This is the switch case alternative in Python. We will also show you how lambda can be helpful in the same example.

Let’s see how it will work by calling a function in Python.

def day_1():
    return 'You selected Sunday'
def day_2():
    return 'You selected Monday'
def day_3():
    return 'You selected Tuesday'
def day_4():
    return 'You selected Wednesday'
def day_5():
    return 'You selected Thursday'
def day_6():
    return 'You selected Friday'

def switch(num):
    dict={
        1: day_1,
        2: day_2,
        3: day_3,
        4: day_4,
        5: day_5,
        6: day_6,
        7: lambda :' You selected Saturday'
    }
    result = dict.get(num, lambda:'Invalid Day')
    return result()

user_input = int(input("Enter Number of Day: "))

print('You selected: ',switch(user_input))
Python Switch Case by Calling a Function

In the above code, we’ve created separate functions for the days. One more function is named switch. This function will decide which day function to call based on user input. In the switch function, there is a dictionary where the sequence of the numbers from 1 to 7 is stored as a key.

Switch case in Python using match statement in Python 3.10

In programming languages like c or C++, there is a direct way to use switch cases in the program. But in Python, there was no direct way to do a switch case in Python.

However, Python introduced a match statement in version 3.10, so it has a direct way to get the expected output.

Let’s see how we use the switch case in Python using the match case statement in Python.

day = input("Enter a number from 1 to 7: ")

match day:
    case "1":
        print("You selected Sunday")
    case "2":
        print("You selected Monday")
    case "3":
        print("You selected Tuesday")   
    case "4":
        print("You selected Wednesday")
    case "5":
        print("You selected Thursday")        
    case "6":
        print("You selected Friday")
    case "7":
        print("You selected Saturday")   
    case _:
        print("invalid input...Try again later")
Switch case in Python using match statement in Python 3.10

In the above code, taking the user input, it will match the input pattern with the case pattern; if it matches the pattern with any case, then it will execute that statement block; otherwise, it will execute case_: block.

READ:  Python Dictionary Find Key By Value

How to Use Switch Case in Python With User Input Using Class Methods

We can also use the class as a switch case in Python, where we can include all the cases as a method of class in Python.

Let’s understand this approach with the practical example of using a switch case in Python with user input.

class Switch:
    def case_1(self):
        print('You selected Monday')
    def case_2(self):
        print('You selected Tuesday')
    def case_3(self):
        print('You selected Wednesday')
    def case_4(self):
        print('You selected Thursday')
    def case_5(self):
        print('You selected Friday')
    def case_6(self):
        print('You selected Saturday')
    def case_7(self):
        print('You selected Sunday')
    def switch(self, cases):
        method = 'case_' + str(cases)
        return getattr(self, method)()

switcher= Switch()

user_input = int(input("Enter Day number: "))

if user_input<8:
    switcher.switch(user_input)
else:
    print("Invalid input, please try again later")
How to Use Switch Case in Python With User Input Using Class Methods

In the above code, we’ve created a class named Switch and separate methods for every day of the week inside the Switch class. Then, we made another method named switch inside the same class, which decides which method to call based on user input.

Then, we check the user input. If the input is less than 8, it should display the selected day; otherwise, it will display Invalid Input.

Conclusion

In this Python article, you learned how to use the switch case in Python with user input. We explored five different methods and approaches with practical examples.

Using a match statement is a direct way to use the switch case in Python; others are alternative ways to get the required output.