Case statement in Python

In this Python tutorial, we will discuss the case statement in Python with the help of some examples. Also, we will discuss the following topics.

  • Does Python have a case statement?
  • How to use case statement in Python?
  • Simple case statement in Python
  • Switch case in Python with example
  • Python switch case default value
  • Case statement dictionary Python
  • Python switch case statement default
  • Switch case in Python using function
  • Switch case in Python using classes and objects
  • Switch case in Python with user input
  • Calculator using switch case in Python
  • Python switch case one line
  • Switch case in Python string
  • Python switch letter case
  • Python switch case boolean
  • Python switch case float
  • Python switch case break
  • Python switch case with condition
  • Python switch case array
  • Python switch statement best practices

Does Python have a case statement?

Most of the languages support the case statement. But, in Python, there is no case statement by default. However, we can make our own functions that we can use as an alternative to the case statement.

Hence, in this article, I will explain how you can create functions in Python that you can use as the case statement.

Read Remove non-ASCII characters Python

How to use case statement in Python?

In Python, you can implement the case statement in many ways. You can use the if-else statement. In that case, you have to use multiple if-else statements for multiple cases.

The second method is to map cases with some functions using dictionaries in Python. You can make a dictionary and make key-value pairs of cases and functions.

The keys will be your conditions and the corresponding values will be the functions that you want to call according to the condition.

Let us discuss some methods with examples to implement the case statement in Python.

Also, Read: Python dictionary of lists

Simple case statement in Python

As explained above, we can use multiple if-else blocks to implement a case statement in Python. The idea behind this method can be understood with the example below.

if <case variable> == <case 1>:
    <function or statement for case 1>
elif <case variable> == <case 2>:
    <function or statement for case 2>
elif <case variable> == <case 3>:
    <function or statement for case 3>
.
.
.
elif <case variable> == <case n>:
    <function or statement for case n>
else:
    <default case statement or function>

Switch case in Python with example

Suppose you want to print the month’s name of a year according to a specified number. For example, 1 to 12 represents the months of the year from January to December.

In this case, you may want to use the case statement. But, let us see how we can implement this with the help of an if-else statement.

def printMonth(num):
    if num == 1:
        month =' January'
    elif num == 2:
        month = 'February'
    elif num == 3:
        month = 'March'
    elif num == 4:
        month= 'April'
    elif num == 5:
        month= 'May'
    elif num == 6:
        month = 'June'
    elif num == 7:
        month = 'July'
    elif num == 8:
        month = 'August'
    elif num == 9:
        month= 'September'
    elif num == 10:
        month= 'October'
    elif num == 11:
        month= 'November'
    elif num == 12:
        month= 'December'
    return month

print('Month is:', printMonth(10))
  • In the above function, we are assigning the name of the month in every if block according to the specified number.
Simple case statement in Python
The function returned the expected month name

You can see that we supplied the number 10 as the input and the function returned October. Similarly, we have defined all the cases from 1 to 12 in the function.

In this way, you can use the if-else statement to implement the case statement in Python.

Read: Python dictionary extend

Python switch case default value

While implementing the switch case statement in python using the if-else statement, you can define the default case value in the last else section of the program.

Take the example of the program that we executed in the above section. If a person enters a number except from 1 to 12, the program will throw an error.

However, you can define a default case in an else section. I have implemented the same program with a default case:

def printMonth(num):
    if num == 1:
        month =' January'
    elif num == 2:
        month = 'February'
    elif num == 3:
        month = 'March'
    elif num == 4:
        month= 'April'
    elif num == 5:
        month= 'May'
    elif num == 6:
        month = 'June'
    elif num == 7:
        month = 'July'
    elif num == 8:
        month = 'August'
    elif num == 9:
        month= 'September'
    elif num == 10:
        month= 'October'
    elif num == 11:
        month= 'November'
    elif num == 12:
        month= 'December'
    else:
        month= 'Invalid Month'
    return month

print('Month is:', printMonth(13))

This time I am passing 13 as the case value. Let us see the output now.

Python switch case default value
Default case value

You can see that the default case value is returned. In this way, you can define a default case in a switch case implementation in Python using the if-else statement.

Read: Python string to list

Case statement dictionary Python

You can also implement the case statement in Python using dictionaries. Let us see how we can implement this.


    dict={
        <case 1>: <function or statement for case 1>,
        <case 2>: <function or statement for case 2>,
        <case 3>: <function or statement for case 3>,
        .
        .
        .
        <case n>: <function or statement for case n>
    }

To execute the statement or function for a particular case, you can use the get() method of the Python dictionary.

dict.get(<case value>), <default case value>)

Now let us see an example. Consider the following python code.

dict={
    1: 'Sunday',
    2: 'Monday',
    3: 'Tuesday',
    4: 'Wednesday',
    5: 'Thursday',
    6: 'Friday',
    7: 'Saturday'
}

print('Entered Number is 2. Day of the week is:',dict.get(2))

We have created a dictionary to use the case statement. The numbers from 1 to 7 will be the different cases and we will print the day of the week corresponding to those numbers.

We have used the get() function to get the value for the supplied key.

Case statement dictionary Python
The output of the program

Python switch case statement default

Suppose in the above program, we try to implement a case value that is not defined in the dictionary. In that case, we will get None as the output.

However, we can define our own default case value, in case the value is not present in the dictionary.

For this, we can pass the default value to the get() method while retrieving the dictionary values. We have to pass the default value as the second argument in the get() method.

The above program with a default case value can be rewritten as:

dict={
    1: 'Sunday',
    2: 'Monday',
    3: 'Tuesday',
    4: 'Wednesday',
    5: 'Thursday',
    6: 'Friday',
    7: 'Saturday'
}

print('Entered Number is 9. Day of the week is:',dict.get(9, 'Not Valid'))
python switch case statement default
Default case output

The get() function tried to retrieve the value of key 9. But, as this key value was not in the dictionary, the get() function returned the default value i.e. Not Valid.

Thus. in this way, you can define the default case value in the switch case implementation in Python using a dictionary.

Read: Python Dictionary Copy

Switch case in Python using function

Now let us execute the same example with a function and make it more usable.

def switch(num):
    dict={
        1: 'Sunday',
        2: 'Monday',
        3: 'Tuesday',
        4: 'Wednesday',
        5: 'Thursday',
        6: 'Friday',
        7: 'Saturday'
    }
    return dict.get(num, 'Invalid Day')
num= 5
print(' The number is:', num, 'and the day is:',switch(num))
python dict case statement
The output of the program

You can see that our function is working as expected. You can enter the case value in the num variable.

Switch case in Python using classes and objects

You can also implement the switch case functionality in Python with classes and objects.

The idea behind this approach is to create a class for switch function and define all the methods or functions inside the class for every case.

Later, we will create an object of this class and call a function of this class and specify the case value as the argument.

class Switch:
    # Defining a function for every case
    def case_1(self):
        print('January')
    def case_2(self):
        print('February')
    def case_3(self):
        print('March')
    def case_4(self):
        print('April')
    def case_5(self):
        print('May')
    def case_6(self):
        print('June')
    def case_7(self):
        print('July')
    def case_8(self):
        print('August')
    def case_9(self):
        print('September')
    def case_10(self):
        print('October')
    def case_11(self):
        print('November')
    def case_12(self):
        print('December')

    # Defining a function to decide which function to call
    def circle(self, cases):
        method = 'case_' + str(cases)
        return getattr(self, method)()
        
# Declaring an object
switcher= Switch()

# Calling the switch case method
switcher.circle(12)
switch case python with arguments
The expected function is called

In the above code, the circle function will decide which case is invoked and which function to call.

We are concatenating the two strings case_ and str(cases) to make the function name. Then we will pass this string to the getattr() function.

The getattr() function takes two arguments. First is the object name, which is self in our case and the second is the name of the attribute of the object that we want to return. This attribute name will be defined as a string.

In this way, you can use classes and objects to implement the switch case functionality in Python.

Read: Python dictionary multiple keys

Switch case in Python with user input

Let us see an example in which we will take input from the user and return a result accordingly. Look at the Python code below;

def returnUserInfo(user_id):
    user_info={
        1001: 'James',
        1002: 'Rosy',
        1003: 'Ben',
        1004: 'John',
        1005: 'Mary'
    }
    return user_info.get(user_id, 'Invalid User ID')

user_id= int(input('Enter the user ID:'))
print(returnUserInfo(user_id))
  • In the above code, you can compare the user_id variable with the case variable of a case statement.
  • The user_id is passed to a function that is the alternate of the switch statement. The function returns the result according to the user_id value.
  • You can compare the second argument of the get() function with the default case in the switch case statement.

Calculator using switch case in Python

Let us create a calculator for a better understanding of how we can implement the switch case statement in Python. We can use various methods, but for this example, we will use the mapping method using a Python dictionary.

# Defining the arithmetic functions

def addition(num1, num2):
    return num1 + num2
def subtraction(num1, num2):
    return num1 - num2
def multiply(num1, num2):
    return num1 * num2
def realDivision(num1, num2):
    return num1 / num2
def intDivision(num1, num2):
    return num1 // num2
def modulus(num1, num2):
    return num1 % num2

# Defining the switch function

def switch(operation, num1, num2):

    dict={
        1: addition(num1, num2),
        2: subtraction(num1, num2),
        3: multiply(num1, num2),
        4: realDivision(num1, num2),
        5: intDivision(num1, num2),
        6: modulus(num1, num2)
    }
    return dict.get(operation, 'Invalid Operation')

# Taking the operands from the users

num1= int(input('Enter the first number: '))
num2= int(input('Enter the second number: '))

# Taking user input to choose an operation

print('''Press 1 for Addition
Press 2 for Subtraction
Press 3 for Multiplication
Press 4 for real number Division
Press 5 for integer Division
Press 6 for finding the remainder after division''')
num= int(input('Enter a number of your choice: '))

# Calling the switch function
print('Result is: ', switch(num, num1, num2))
  • In the above Python code, we have defined separate functions for various arithmetic operations.
  • Then we are using a dictionary inside a switch function in which we are storing the function calls in a key value pair.
  • This switch function will take three arguments:
    • operation: The value between 1 to 6 deciding the function to get called.
    • num1: The first operand on whihc the operation will be performed.
    • num2: The second operand.
  • If a valid number is eneterd i.e. between 1 to 6, then the switch function will return the arithmetic function specified. Otherwise, the switch function will return a default value i.e. Invalid Operation.
  • The two operands will be passed to the function that will be exceuted and the function will return the result.

Let us see the output in different cases:

The output for case 1 i.e. addition:

Calculator using switch case in Python
Valid Input

The output for an invalid case:

Calculator using switch case in Python
Invalid input

Thus, you might have learned how you can create a calculator in Python by implementing a function as a switch case statement.

Read: Remove character from string Python

Python switch case one line

In this section, we will use the lambda functions to implement the above calculator program in Python.

We will implement all the arithmetic functions in a single line. This means we will not create functions separately. Instead, we will create lambda functions inside the switch case dictionary and map with the input.

# Defining the switch function

def switch(operation, num1, num2):

    dict={
        1: (lambda x, y : x + y),
        2: (lambda x, y : x - y),
        3: (lambda x, y : x * y),
        4: (lambda x, y : x / y),
        5: (lambda x, y : x // y),
        6: (lambda x, y : x % y)

    }
    return dict.get(operation, 'Invalid Operation')(num1, num2)

# Taking the operands from the users

num1= int(input('Enter the first number: '))
num2= int(input('Enter the second number: '))

# Taking user input to choose an operation

print('''Press 1 for Addition
Press 2 for Subtraction
Press 3 for Multiplication
Press 4 for real number Division
Press 5 for integer Division
Press 6 for finding the remainder after division''')
num= int(input('Enter a number of your choice: '))

# Calling the switch function
print('Result is: ', switch(num, num1, num2))
Python switch case one line
lambda function for addition is called

Note that while retrieving the function using the get() method, we need to pass the input values i.e. (num1, num2).

Thus, you might have learned how you can use the lambda functions to complete the calling function in one line inside a switch case statement implementation in Python.

Read: Python find max value in a dictionary

Switch case in Python string

In the above sections, I only demonstrated the examples in which I checked for only the numeric variable as the case. But sometimes you also need to check any string variable as the case in a case statement.

I will map some string values to some functions in a dictionary. Then I will call a function corresponding to the supplied key i.e s string case. Look at the example below:

def area():
    radius = float(input('Enter the radius of circle:'))
    print('Area of circle is: ', 3.14 * radius * radius)
def circumference():
    radius = float(input('Enter the radius of circle:'))
    print('Circumference of circle is:', 2 * 3.14 * radius)
def default():
    print('Invalid Operation')

def switch(operation):
    dict={
        'area' : area,
        'circumference' : circumference
    }
    return dict.get(operation, default)()

operation = input('Enter an operation to perform on circle:')
switch(operation)
  • The above program has two cases i.e. finding the area of a circle or finding the circumference of a circle.
  • We are passing a string value to our switch function and the switch function is calling a function according to the given string value.
  • A default function will be called if the string value is not present in the dictionary.
  • Note that in the dictionary, we are just storing the references of the functions to be executed and the desired function is called in the return statement.
  • Let us see the output:
Switch case in Python string2
The output of every string case

You can see the output of every string case passed to the switch function.

Thus, you might have learned how you can implement the switch case functionality for strings in Python.

Read: How to create an empty Python dictionary

Python switch letter case

In this section, I will show you an example in which you can use the switch case implementation for letters.

I have created a simple example to check if the entered alphabet is a vowel or a consonant. I have mapped all the vowels with the string ‘Vowel‘ depicting that the character is a vowel.

And, if we give a consonant as the input, the default case will be returned i.e ‘Consonant’.

def switch(alphabet):
    dict={
        'a': 'Vowel',
        'e': 'Vowel',
        'i': 'Vowel',
        'o': 'Vowel',
        'u': 'Vowel',
        'A': 'Vowel',
        'E': 'Vowel',
        'I': 'Vowel',
        'O': 'Vowel',
        'U': 'Vowel',
    }
    return dict.get(alphabet, 'Consonant')

alphabet= input('Enter an alphabet to check: ')
print('The entered alphabet is: ', switch(alphabet))
  • Let us give an vowel character as the input.
python switch letter case
Output when a vowel is entered
  • Now let us give a consonant as the input.
python switch letter case
Output when a consonant is entered

Thus, you might have learned how you can implement a switch case statement in Python and checking a letter value as the case.

Read: Python Dictionary to CSV

Python switch case boolean

If you want to implement the switch case statement for boolean use cases, you can simply use the if-else statement. Let me demonstrate this with an example.

def switch(case):
    if case == True:
        print('You have excuted the True function')
    elif case == False:
        print('You have exected the False function')
    else:
        print('You have executed the default case function')

switch(False)
switch(True)
switch('Default String')

In the above code, we have defined three boolean use cases:

  • True
  • False
  • Default use case if either of the True or the False is not specified.
Python switch case boolean
Switch case implementation for boolean use cases

In this way, you can implement the switch case functionality in Python for boolean use cases.

Read: Python convert dictionary to an array

Python switch case float

If you want to pass a float value as the case in a switch-case statement, you can do it in the same way as we did in the case of any integer value. Let me show you this with an example.

def switch(case):
    dict={
        1.5 : 'You have choosen the case for 1.5',
        1.6 : 'You have choosen the case for 1.6',
        2.5 : 'You have choosen the case for 2.5',
        2.6 : 'You have choosen the case for 2.6',
        2.7 : 'You have choosen the case for 2.7',
    }
    return dict.get(case, ' Undefined Case ')

print(switch(2.5))
print(switch(5.6))
Python switch case float
Switch case for the float values

We mapped the float values to the result that we want to be printed. We are using the get() method to return the value corresponding to the supplied key i.e a float case value.

In this way, you can use the float values as the case input in switch case implementation in Python.

Python switch case break

In Python, there is no switch case statement and thus, no break statement in the switch case in Python. However, we use different methods to implement this switch case functionality.

In other programming languages, you expect from a break statement that it will break the flow of a particular case.

In other words, if you have defined some statements under a case and you want to terminate that case after some statements, you will use the break statement and the flow of the program will move to the next case.

If the case is the last one, the switch case structure will be terminated.

However, if you implement the switch case functionality using any of the methods, you will find that there is no need for the break statement.

Because a function is called for a particular case. When all the statements are executed inside the function, the control or flow of the program automatically moves to the next line. Thus, there is no need for the break statement.

Read: Python dictionary of tuples

Python switch case with condition

In this section, I will explain how you can use the case statement to deal with a range of numbers as the case value.

For example, if the case value is greater than 10 and less than 2. In such cases, you may want to write the switch case statement to deal with a range of numbers.

In this kind of scenario, you should use the if-else method to implement the switch case functionality. Because you have to compare the case value with the if-else statement. Also, this method is the fastest method in terms of performance.

Let me show you an example.

def switch(marks):
    if marks >=91 and marks <=100:
        print("Your Grade is A")
    elif marks >=71 and marks <91:
        print("Your Grade is B")
    elif marks >=51 and marks <71:
        print("Your Grade is C")
    elif marks >=35 and marks <51:
        print("Your Grade is D")
    elif marks >=0 and marks <35:
        print("Your Grade is F")
    else:
        print("Invalid Marks Entered!")

switch(61)
Python switch case greater than
Switch case output for a range

In this way, you can implement the switch case functionality in Python for a range of input values.

Read: Python dictionary pop

Python switch case array

Several times you might have faced some scenarios when you want to pass an array to a case statement. In Python. we implement the concept of the array with the help of a list.

Hence, in this section, I will explain how you can implement the switch case statement in Python with arrays. I will implement an example in two ways.

Suppose we have a boolean array in Python that we want to use as a case in the switch case statement. For example, [1, 0, 1, 0, 1] or [True, False, True, False, True].

Implementation 1: Using the if-else structure

Look at the code written below:

# defining the functions to execute
def case1():
    print('This is the function for the array [0, 1, 1, 0, 1] using if else')

def case2():
    print('This is the function for the array [0, 0, 0, 1, 1] using if else')

def case3():
    print('This is the function for the array [0, 0, 0, 1, 1] using if else')

# defining the switch function
def switch(arr):
    if arr == [0, 1, 1, 0, 1]:
        case1()
    elif arr == [0, 0, 0, 1, 1]:
        case2()
    elif arr == [1, 1, 1, 0, 0]:
        case3()
    else:
        print('Invalid Case')

# Calling the switch function

arr= [0, 0, 0, 1, 1]
switch(arr)
arr1= [0, 0, 0, 0, 0]
switch(arr1)

In the above code, you can see that we are passing a list to the switch function. Then the switch function returns the function according to the specified case.

I have called the switch function for two cases i.e. a valid and an invalid case. You can see the output for both the cases in the below image.

Python switch case array
Switch case for array using if-else

Implementation 1: Using the dictionary mapping method

Now I will create the same switch functionality, but using the dictionary mapping method this time.

# defining the functions to execute
def case1():
    print('This is the function for the array [0, 1, 1, 0, 1] using dictionary mapping')

def case2():
    print('This is the function for the array [0, 0, 0, 1, 1] using dictionary mapping')

def case3():
    print('This is the function for the array [0, 0, 0, 1, 1] using dictionary mapping')

def default():
    print('Default Case')

# defining the switch function
def switch(arr):
    dict={
        '[0, 1, 1, 0, 1]': case1,
        '[0, 0, 0, 1, 1]': case2,
        '[0, 0, 0, 1, 1]': case3
    }
    return dict.get(arr, default)()

# Calling the switch function
arr = '[0, 1, 1, 0, 1]'
switch(arr)
arr1 = '[1, 1, 1, 1, 1]'
switch(arr1)

You can notice one thing that I have passed the list as a string to the switch function. This is because this list will be our key in the dictionary and you cannot assign a list as a key in a Python dictionary. Thus, we are converting the list into a string.

Python switch case array
Switch case for an array using the dictionary mapping method

You can choose one of the methods that you find more convenient to use. But before deciding take a look at the next section in which I have explained which method you should select according to your requirements.

Read: Python loop through a list

Python switch statement best practices

In this section, I will explain to you the best practices to implement the switch case functionality in Python for various techniques that we discussed above.

  • If you have a very few cases to check you should use the if-else method for implementing the switch case fucntionaliy.
  • This is because, this method is very fast in performance if you have a few if-else statements. Also, it is not very difficult to write few number of statements.
  • But, if you have large number of cases to check, you should use the dictionary mapping method. It is better than the if else method in large number of cases.
  • If you want to check a range as a single case, you have to use the if else method.
  • You should avoid the use of classes and objects method for implementing the switch case functionality. This is because, it is difficult and complex method for implementation. Also, it is not much effificient in terms of performance.

These are some points that you should keep in your mind while selecting an appropriate method for implementing the switch case functionality in Python.

You may like the following Python tutorials:

So, in this article, we have discussed the case statement in Python with the help of some examples. Also, we have covered the following topics.

  • Does Python have a case statement?
  • How to use case statement in Python?
  • Simple case statement in Python
  • Switch case in Python with example
  • Python switch case default value
  • Case statement dictionary python
  • Python switch case statement default
  • Switch case in Python using function
  • Switch case in Python using classes and objects
  • Switch case in Python with user input
  • Calculator using switch case in Python
  • Python switch case one line
  • Switch case in Python string
  • Python switch letter case
  • Python switch case boolean
  • Python switch case float
  • Python switch case break
  • Python switch case with condition
  • Python switch case array
  • Python switch statement best practices