Python Switch Case with Examples

FREE Online Courses: Elevate Skills, Zero Cost. Enroll Now!

Looking at the word ‘switch’, are you remembering the switch used to turn the devices on and off? Wondering what is switch doing in Python?

In a programming language, the switch is a decision-making statement. In this article, we will learn the working of the switch case and its implementation in Python. So, let us start with the introduction to the switch.

Introduction to Python Switch

As said above, the switch is a construct that can be used to implement a control flow in a program. It can be used as an alternative to the if-else statements or the elif ladder when we have a single variable/ an expression that we use to make the decision.

Using this instead of the multiple if-else statements makes the code look cleaner, quicker, and more readable. It works by executing the code block under a corresponding case that is satisfied.

Let us look more at the work in the next section.

Working of Switch Case in Python

Switch statements mainly consist of the condition and different cases which are checked to make the condition. It takes a value or a variable or an expression as an input.

Each case corresponds to a particular value. It checks if any of the cases is equal to the input and based on that respective statement(s) is(are) executed. It also allows us to write a default case, which is executed if none of the cases are True.

Let us see an example of checking the day of the week based on the number given to know the working of the switch statement. It takes the number as input and checks it with each case till it reaches the True case.

Starting from 0 to 6, it checks till the number is equal to one of these values. And at one point if it matches, the corresponding day of the week is printed. If none of the cases match, then it executes the default case and prints that the input is invalid.

Look at the below flow chart for further understanding of the working of loops.

Working of Switch in Python

Unlike the other programming languages like C, C++, Java, etc., in Python, there is no built-in switch construct. But it allows us to implement the switch statements using others in different ways. We can either use the following to do so:
1. a dictionary
2. a class

Implementing Switch in Python using elif ladder

Before using the other constructs, first, let us use the elif ladder to implement the switch control. The following code shows an example of giving the output as the number in words.

Example on implementing switch case using elif ladder:

def num_in_words(no):
    if(no==1):
        print("One")
    elif(no==2):
        print("Two")
    elif(no==3):
        print("Three")
    else:
        print("Give input of numbers from 1 to 3")

    
num_in_words(3)

num_in_words(4.5)

Output:

Three

Give input of numbers from 1 to 3

Here, when we call the function, the elif ladder is executed. And the number given as input is checked with the conditions in the brackets and the corresponding block is executed when the condition is met. If none of the conditions satisfy, the else block executes, asking to give correct numbers.

Implementing Python Switch using Dictionary

We can use a dictionary to implement the switch case. We know that the dictionary holds the key-value pairs. It can have the keys as the condition/ element to be checked and the values as the elements to be printed or the functions to be executed.

Using elements as the values of the dictionary

We can use the elements to be printed as the values of the dictionary and use the get() function to get the corresponding value of a key.

The following code shows an example of printing a corresponding vowel.

Example on implementing switch case using the dictionary:

def vowel(num):
    switch={
      1:'a',
      2:'e',
      3:'i',
      4:'o',
      5:'u'
      }
    return switch.get(num,"Invalid input")

vowel(3)

vowel(0)

Output:

‘i’

‘Invalid input’

Here when we call the function by giving a number as an input, then it executes the dictionary and the return statement. The return statement contains the get() function of the dictionary, which outputs the value of the corresponding key. Here the key is the number.

The second argument of the get() is the default value that is returned when the key is not found. So, it returns “Invalid input” if the number is not in the range of 1 to 5.

Using functions/lambda functions as the values of the dictionary

We can also use the functions as the values of the dictionary. Then we can use the get() of the dictionary to call that particular function. This will help us write more operations using the switch, than just printing an element on finding a matching key.

The following code gives an example of using the functions to do a particular operation based on the input operand.

Example on implementing switch case using the dictionary with functions as values:

def add():
    return n+m

def subs():
    return n-m

def prod():
    return n*m

def div():
    return m/n

def rem():
    return m%n

def operations(op):
    switch={
       '+': add(),
       '-': subs(),
       '*': prod(),
       '/': div(),
       '%': rem(),
       }
    return switch.get(op,'Choose one of the following operator:+,-,*,/,%')

operations('*')

operations('^')

Output:

36

‘Choose one of the following operator:+,-,*,/,%’

Here the same flow as in the case when we printed a value in the previous case. When we call the function ‘operations’ by giving the operator as the input, the dictionary and the return statements are executed.

And the get()) function in the return statement checks for the key, here the operator, and calls the corresponding functions. Then outputs the value returned by the respective function.

If the key is not found, it prints to choose the operators in the dictionary, which is given as the second argument.

Implementing Python Switch using Class

Besides using the dictionary, we can also use Python classes to implement the switch construct. The classes in simple words are the collections of variables and functions that act as a single unit. We can define a class using a ‘class’ keyword’.

The below code shows an example of implementing the switch to get the moth given the number, using the class.

Example on implementing switch case using the class:

class Month(object):
    def month_1(self):
        print("January")
    def month_2(self):
        print("February")
    def month_3(self):
        print("March")
    def month_4(self):
        print("April")
    def month_5(self):
        print("May")
    def month_6(self):
        print("June")
    def month_7(self):
        print("July")
    def month_8(self):
        print("August")
    def month_9(self):
        print("September")
    def month_10(self):
        print("October")
    def month_11(self):
        print("November")
    def month_12(self):
        print("December")
    def getMonth(self,no):
        name_of_method="month_"+str(no)
        method=getattr(self,name_of_method,lambda :'Give an input as an integer from 1 to 12')
        return method()

  
mo=Month()
mo.getMonth(5)

mo.getMonth(0.5)

Output:

May

‘Give an input as an integer from 1 to 12’

Here a function is defined for each month. And the function ‘getMonth()’ has the main body of what we want to implement. This function takes a number as an input and combines it with the string ‘month_’ to get the corresponding function name. The method is called using the ‘getattr()’ method to call the particular function. Then we return the output of the called function.

If the function is not available, then we call the default function given as the second argument to the ‘getattr()’. Here we gave a lambda function asking to give correct input.

Interview Questions on Python Switch

Q1. Write a switch case program to check if a letter is a vowel

Ans. We can write the vowels as the keys of the dictionary and value as the string ‘It is a vowel’. And the default case printing it is not a vowel

Example of checking if a letter is vowel or not:

def operations(letter):
    switch={
       'a': "It is a vowel",
       'e': "It is a vowel",
       'i': "It is a vowel",
       'o': "It is a vowel",
       'u': "It is a vowel",
       }
    return switch.get(letter,"It is a not a vowel")

operations('a')

Output:

‘It is a vowel’

‘It is a not a vowel’

Q2. Write a program to check if the function is positive or negative or zero.

Ans. We can write a function to check the sign of the number. In this function we can first check if the number is a digit or not using the built-in function isdidigt(), to prevent errors. Then we can call that function in the get() method and based on the output of this function we can write the switch cases.

Example of checking sign of a number:

def sign(n):
    if(~n.isdigit()):
        return ""
    if n>0:
        return 'p'
    if n<0:
        return 'n'
    return 'z'


def switch(no):
    switch={
       'p': "Positive",
       'n': "Negative",
       'z': "Zero",
       }
    return switch.get(sign(no),"Invalid input")

switch(4)

switch('l')

Output:

‘Positive’

‘Invalid input’

Q3. Write a program to check if a mail is correct, by checking if it contains the character ‘@’ and ‘.com’.

Ans. We can write a function to check if the character occurs in the mail by using the membership operator.

Example to check the validity of a mail id:

def check(mail):
    if('@' in mail and '.com' in mail):
        return True
    return False

def switch(mail):
    switch={
       True: "It is vaild",
       False: "It is invalid",
       }
    return switch.get(check(mail),"Please give proper input")

switch('[email protected]')

switch('xyz@mail')

Output:

‘It is vaild’

‘It is invalid’

Q4. Write a program to check if the first number is divisible by 2, 3, or 5.

Ans. We can write a function to check the divisibility and then based on the results we can give appropriate results. Then on calling the function we can check the divisibility with either 2, 3, or 5.

Example to check validity divisibility:

class Divisibility():

    def div2(self,n):
        return (n%2==0)
    def div3(self,n):
        return n%3==0
    def div5(self,n):
        return n%5==0
    def divide(self,no1,no2):
        name_of_method="div"+str(no2)
        method=getattr(self,name_of_method,lambda :'Give an input as an integer 2, 3 or 5')
        return method(no1)

d=Divisibility()
d.divide(6,3)

Output:

True

Q5. Write a function to print the price of the following in the menu on giving the input as either of the numbers from 1 to 5.
1: The price of Pizza is Rs.80
2: The price of Burger is Rs.100
3: The price of Chicken fires is Rs.150
4: The price of a Cool Drink is Rs.30
5: The price of Noodles is Rs.50

Ans. Below is the example on writing menu using Python switch:

class Menu():
    
    def item1(self):
        print("Price of Pizza is Rs.80")
    def item2(self):
        print("Price of Burger is Rs.100")
    def item3(self):
        print("Price of Chicken fires is Rs.150")
    def item4(self):
        print("Price of Cool Drink is Rs.30")
    def item5(self):
        print("Price of Noodles is Rs.50")    
    
    def price(self,no):
        item_price="item"+str(no)
        method=getattr(self,item_price,lambda :'Invalid')
        return method()

d=Menu()
d.price(3)
d.price(6)

Output:

Price of Chicken fires is Rs.150
‘Invalid’

Quiz on Python Switch Case

Conclusion

In this article, we learned about switch-case statements, their working, and their implementation in different ways. In the end, we saw some practice questions.

Hoping that you learned something new from this article. Happy learning!

Your opinion matters
Please write your valuable feedback about PythonGeeks on Google | Facebook


3 Responses

  1. Aruna says:

    Pls send what type of apptitude questions repeatedly asked in interview

  2. Mike says:

    This article is obsolete! Python 3.10 has built-in switch statement.

  3. code nhu cac says:

    need print() to receive the anser, code nhu cc

Leave a Reply

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