Table of Contents
A selection control statement in Python is called a Switch Case. Once, the switch expression is evaluated. The expression’s value is compared to the values of each case; if a match is found, the accompanying block of code is run. Python, unlike other languages, lacks built-in switch case statements, thus we must build them using alternative approaches.
What is Switch Case in Python?
The if statement decides whether or not the condition is true. If the condition is true, it evaluates the indented expression; if the condition is false, it evaluates the indented phrase beneath else. When we need to execute several conditions, we may include as many elif conditions as we need between the if and else conditions. Long if statements that compare a variable to numerous integral values are replaced with switch case statements.
The switch statement is a branch statement with many paths. It allows you to easily route execution to various areas of code based on the value of the expression.
A switch statement is a control statement that allows a value to shift execution control.
But unline different languages; python doesn’t have its inbuilt switch case statements.
“Ready to take your python skills to the next level? Sign up for a free demo today!”
How to implement Python Switch Case?
1: Which of the following data types is immutable in Python?
Python, unlike C++/Java, has an inherent Switch Case statement. There are various approaches to implementing Switch Case statements in Python. These are the methods:
1. With the help of dictionaries
- By using functions
- By using Lambdas
2. With the help of classes
3. With the help of if-elif-else statements
Let’s see each of the methods to implement the python switch case statement one by one with the help of examples. Read along to know more.
Python Switch Case using Dictionary
If you’re acquainted with the Dictionary pattern of keeping a collection of items in memory using key-value pairs. As a result, when we use the Dictionary data type to replace the Switch case statement, the key value of the dictionary data type functions as cases in a switch statement. Furthermore, there are two approaches to using Dictionary to construct a Switch Case. They are as follows:
- Using Functions
- Using Lambda Functions
Python Switch Case Using Functions
When we use the Dictionary data type to replace the Switch case statement, the dictionary data type’s key functions as cases in a switch statement. We must define certain functions that are used as values in dictionaries. When we use keys to call these values, the specific function is executed, and we obtain the required output.
We will create a switch case in Python using dictionaries and functions.
Example
In this example, we are converting a number to its number name.
Code:
def one():
return "one"
def two():
return "two"
def three():
return "three"
def four():
return "four"
def five():
return "five"
def six():
return "six"
def seven():
return "seven"
def eight():
return "eight"
def nine():
return "nine"
def default():
return "no spell exist"
numberSpell = {
1: one,
2: two,
3: three,
4: four,
5: five,
6: six,
7: seven,
8: eight,
9: nine
}
def spellFunction(number):
return numberSpell.get(number, default)()
print(spellFunction(3))
print(spellFunction(10))
“Experience the power of our web development course with a free demo – enroll now!”
Output:
three
no spell exist
We write many functions that return the number names of the numbers.
Then we establish a dictionary in which we store various key-value pairs.
We constructed the main function after constructing the Dictionary, which takes user input to find the number name.
Finally, we invoked the function to produce the appropriate output.
Python Switch Case Using Lambdas
We will create a switch case in Python using dictionaries and lambda functions. Lambda functions are short anonymous functions that can have n arguments but only one expression.
When we use the Dictionary data type to replace the Switch case statement, the dictionary data type’s key functions as cases in a switch statement. We must define anonymous lambda functions that are treated as values in dictionaries. When we use keys to call these values, the specific function is executed, and we obtain the required output.
Let’s understand the basics of lambda functions.
Syntax of Lambda Function
lambda parameters: expression
We have to use a lambda keyword to create the lambda function; then, we have to pass parameters and expressions to it with : separating them.
Code:
a = lambda number: number*10
print(a(2))
Output:
20
Explanation
- We have created a lambda function that accepts one parameter and returns a single expression, which returns the number by multiplying it by 10.
- Then, we print the variable by passing a number to it.
- In the end, we got the desired output.
Let’s move to the example to understand how we can use dictionaries with the help of lambda functions for implementing switch-case statements in python.
Example
In this example, we are converting a number to its number name.
Code:
def one():
return "one"
def two():
return "two"
def three():
return "three"
def spellFunction(number):
numberSpell = {
1: one,
2: two,
3: three,
4: lambda: "four"
}
return numberSpell.get(number, lambda: "no number spell exist")()
print(spellFunction(1))
print(spellFunction(7))
Output:
one
no number spell exist
We write many functions that return the number names of the numbers.
Then, in the main function, we established a dictionary in which we kept various key-value pairs.
We utilized the lambda function within the Dictionary.
If the number name is accessible in Dictionary, this main method returns it. If the value is not accessible, the default value is returned.
Finally, we invoked the function to produce the appropriate output.
“Experience the power of our web development course with a free demo – enroll now!”
Switch Case using Python Classes
Python Classes may be used to implement Switch Case in Python. In Python, a class is a collection of attributes and functions. Let’s look at an example to understand how we can use classes to implement switch situations.
We must utilize the getattr method, which is required for class-based switch case implementation. Let’s take a quick look at this function.
Syntax
getattr(object, name, default)
This is the syntax of getattr, which accepts three parameters object, name, and default. All three parameters are explained below. Read along to know more.
Parameters
The getattr accepts three parameters used for implementing conditional statements (switch case) using classes. These parameters are:
- object(MANDATORY PARAMETER): object name whose attribute is to be returned.
- name(MANDATORY PARAMETER): string that contains the attribute name of the object.
- default(OPTIONAL PARAMETER): if the attribute is not present in the object, then the default statement is returned.
Return Value
This function returns the name of the attributes present in the object, which finally gives us the output. If the attribute is not present, we will get a default value.
Example
We are going to create an example in which we are checking whether the entered digit is binary or not. If it is binary_0, our function will return zero as an output. On the other hand, if it is binary_1, our function will return one as an output, but if the digit entered is other than 0 & 1, then our code will return not a binary digit. Let’s code this example for better understanding.
Code:
class binaryOrNot():
def mainFunction(self, i):
method_name = 'binary_' + str(i)
method = getattr(self, method_name, lambda: 'not a binary digit')
return method()
def binary_0(self):
return 'zero'
def binary_1(self):
return 'one'
binary = binaryOrNot()
print(binary.mainFunction(1))
Output:
Explanation
To begin, we constructed a class that would tell us whether the number supplied is binary or not.
Then, within the class, we write several methods to determine whether a number is binary or not.
We used the function getattr() to validate the conditions.
Then, in Python, we invoked the class and utilized its method to implement the switch case.
Python Switch Case using if-elif-else
In Python, the if…elif…else statement is used for decision-making, and it may be replaced with a switch case in python with all the switch conditions in the if and elif parts and the default condition in the else section.
The if statement decides whether or not the condition is true. If the condition is true, it evaluates the indented expression; if the condition is false, it evaluates the indented phrase beneath else. When we need to execute several conditions, we may include as many elif conditions as we need between the if and else conditions.
Syntax
if(condition):
statement
elif(condition):
statement
else:
statement
This is the if-elif-else chain where we have to pass the condition into the if & elif, and else is the default statement that gets executed if no conditions above it are false.
Example
Suppose you have a number stored in the variable, and you have to check whether a number is negative, in between 1-10, or greater than 10. Let’s code this problem.
Code:
number = 15
if (number < 0):
print('number is a negative number')
elif (1 <= number <= 10):
print('number lies in between of 1 and 10')
else:
print('number is greater than 10')
Output:
number is greater than 10
First, we assigned a numerical value to a variable.
The conditional expressions are then applied to the if and elif blocks.
We return the statement from these blocks/ after giving the criteria to if-elif.
Finally, we employ the else statement, which is used when none of the requirements listed above are met.
“Get hands-on with our python course – sign up for a free demo!”
Application of Switch Case in Python
As we saw in the introduction section that MENU DRIVEN PROGRAMS requires a switch case to get implemented. We will write code here to create a menu-driven program with the help method if-elif-else statements. Let’s code it for better understanding.
Code:
print('Hai')
print('1. visit the python hub')
print('2. visit DSA hub')
print('3. visit the java hub')
print('4. more')
print('input the suitable option in the next line:')
textInput = int(input())
if (textInput == 1):
print('Thank you. We are redirecting to the python hub.')
elif (textInput == 2):
print('Thank you. We are redirecting to DSA hub.')
elif (textInput == 3):
print('Thank you. We are redirecting to the java hub.')
elif (textInput == 4):
print('Thank you. We are redirecting to more section.')
else:
print('wrong input')
Output:
Hai
1. visit the python hub
2. visit DSA hub
3. visit the java hub
4. more
input the suitable option in the next line:
2
Thank you. We are redirecting to DSA hub.