Switch Case in Python

Switch Case in Python

6 mins read113 Views Comment
Atul
Atul Harsha
Senior Manager Content
Updated on Jan 17, 2023 09:25 IST

In this article, we are going to discuss these methods and how they are used to implement switch case in Python. So, without further ado, let’s get started.

 

Table of Contents

 

 

Table of content
  • What is switch case statement?
  • Introduction to Switch Case in Python
  • Best Online Courses to Learn Data Science
  • Methods to Implement Switch Case in Python
  • Switch Case Example in Python

What is switch case statement?

 

The switch case statement can be described as a cleaner form of an if-else statement in programming languages like C, C++, Java, etc. The significance of the switch case involves:

 

  • Easy maintenance of the code
  • Easy Debugging
  • Values can be checked and verified more effectively
  • Improved code readability

 

Explore free C courses Explore free C++ courses
Explore free Java courses Explore programming courses

 

Introduction to Switch Case in Python

 

Switch Case in Python is a selection control statement, similar to Python if-else – the switch expression is first evaluated and then compared to each case. If there is a match, the associated block of code is executed, else the control moves forward.

 

switch statement in python 1

 

The above flow chart illustrates the working of the switch case.

 

Using Python switch cases can make the program easier to read and understand because it will not be cluttered by too many if-else statements.

 

 

Best Online Courses to Learn Data Science

Course Name Provider Difficulty Length Register
Data Science A-Z Udemy Beginner to Intermediate 21 hours  Enroll Now
Machine Learning A-Z Udemy Beginner to Intermediate 42.5 hours  Enroll Now
IBM Data Science Professional Certificate Coursera Beginner 3-6 months  Enroll Now
Google Data Analytics Professional Certificate Coursera Intermediate 6 months Enroll Now
Deep Learning Specialization Coursera Beginner to Intermediate 5 months Enroll Now
Master's in Data Science with PGP  Upgrad  Beginner to Intermediate 18 months  Enroll Now

Explore free Python courses

 

Methods to Implement Switch Case in Python

 

1. Using Dictionary

 

A common way to implement a switch statement in Python is to use a dictionary to map cases to their corresponding actions. Here's an example:

 

def run_case(case):\n options = {\n 'case_1': case_1,\n 'case_2': case_2,\n 'case_3': case_3\n }\n options.get(case, default)()\n\ndef case_1():\n print("Running case 1")\n\ndef case_2():\n print("Running case 2")\n\ndef case_3():\n print("Running case 3")\n\ndef default():\n print("Invalid case")\n\nrun_case('case_1') # Output: Running case 1\nrun_case('case_2') # Output: Running case 2\nrun_case('case_4') # Output: Invalid case
Copy code

 

Output:

 

Running case 1\nRunning case 2\nInvalid case
Copy code

 

Explanation:

 

In the above example, we define a function run_case(case) that takes a single argument, case, which represents the case to be executed. We create a dictionary that maps cases to their corresponding functions.

 

Here, we have three cases case_1, case_2, and case_3 that map to the functions case_1(), case_2(), and case_3(), respectively.

 

In the run_case() function, we use the get() method of the dictionary to look up the function associated with the provided case. If the case is found in the dictionary, its associated function is executed. If the case is not found in the dictionary, the default() function is executed.

 

One important thing to note here is that in Python, the cases are strings and the functions are defined separately and are not anonymous.

 

2. Using Classes

 

Another way to implement a switch statement in python is by using classes and polymorphism. Let’s look at the following example:

 

class Case1:\n def execute(self):\n print("This is case 1")\n\nclass Case2:\n def execute(self):\n print("This is case 2")\n\nclass Switch:\n def __init__(self, case):\n self.case = case\n\n def execute(self):\n self.case.execute()\n\ncase1 = Case1()\ncase2 = Case2()\n\nswitch = Switch(case1)\nswitch.execute() # prints "This is case 1"\n\nswitch = Switch(case2)\nswitch.execute() # prints "This is case 2"
Copy code

 

Output:

 

This is case 1\nThis is case 2
Copy code

 

Another way is to use the singleton pattern by adding class methods, to achieve the case like behavior:

 

class Case1:\n def execute(self):\n print("This is case 1")\n\nclass Case2:\n def execute(self):\n print("This is case 2")\n\nclass Case1:\n @classmethod\n def execute(cls):\n print("This is case 1")\n\nclass Case2:\n @classmethod\n def execute(cls):\n print("This is case 2")\n\nCase1.execute() # prints "This is case 1"\nCase2.execute() # prints "This is case 2"
Copy code

 

Output:

 

This is case 1\nThis is case 2
Copy code

 

3. Using Cif-elif Statements

 

Although the above examples show different ways to implement a switch-like functionality in Python, they both have a few limitations –

 

  • They both rely on the names of the cases being provided as strings. This means that if the names of the cases change, the code will have to be updated accordingly.
  • Additionally, both examples can make the code less readable, especially when there are many cases to consider.

 

So, we can use another way to achieve the same effect. By using if-elif statements, where elif represents else-if. Here’s an example how:

 

def run_case(case):\n if case == 'case_1':\n case_1()\n elif case == 'case_2':\n case_2()\n elif case == 'case_3':\n case_3()\n else:\n default()
Copy code

 

This method is more readable and explicit, and it doesn't have the problem of hardcoding cases as strings, but it could be less elegant in case of large number of cases.

 

https://www.naukri.com/learning/articles/switch-statement-in-java/

 

https://www.naukri.com/learning/articles/all-about-switch-statement-in-cpp/
https://www.naukri.com/learning/articles/constructors-in-python-definition-types-and-rules/

 

Switch Case Example in Python

 

Using Dictionary

 

Given below is an example of using a switch-like functionality in Python to handle different types of user input in a simple command-line calculator application:

 

def run_case(operator, num1, num2):\n options = {\n '+': add,\n '-': subtract,\n '*': multiply,\n '/': divide,\n }\n options.get(operator, default)(num1, num2)\n\ndef add(num1, num2):\n print(f"{num1} + {num2} = {num1 + num2}")\n\ndef subtract(num1, num2):\n print(f"{num1} - {num2} = {num1 - num2}")\n\ndef multiply(num1, num2):\n print(f"{num1} * {num2} = {num1 * num2}")\n\ndef divide(num1, num2):\n if num2 == 0:\n print("Cannot divide by 0")\n else:\n print(f"{num1} / {num2} = {num1 / num2}")\n\ndef default(num1, num2):\n print(f"Invalid operator. Supported operators are +, -, *, /.")\n\nwhile True:\n num1 = float(input("Enter first number: "))\n operator = input("Enter operator: ")\n num2 = float(input("Enter second number: "))\n run_case(operator, num1, num2)
Copy code

 

Output:

 

Enter first number: 23\nEnter operator: +\nEnter second number: 2\n23.0 + 2.0 = 25.0\nEnter first number:
Copy code

 

Explanation:

 

In this example, the run_case() function takes three arguments: operator, num1, and num2. The operator argument represents the type of operation to be performed (addition, subtraction, multiplication, or division). The num1 and num2 arguments represent the operands for the operation.

 

The run_case() function uses a dictionary to map operators to their corresponding functions. In this example, we have four operators +, -, *, and / that map to the functions add(num1, num2), subtract(num1, num2), multiply(num1, num2), and divide(num1, num2), respectively.

 

In the run_case() function, we use the get() method of the dictionary to look up the function associated with the provided operator. If the operator is found in the dictionary, its associated function is executed with num1 and num2 as arguments. If the operator is not found in the dictionary, the default(num1, num2) function is executed.

 

The program runs in a while loop, where it prompts user to enter the first number, operator and second number. Then it calls the function run_case to perform the desired operation by passing the operator and operands as arguments.

 

Endnotes

 

Hope this article was helpful for you in understanding switch case in Python. In conclusion, the switch-case statement is not a built-in feature in Python, but it can be implemented using a combination of if-elif-else statements, classes, or using a dictionary that maps the cases to its corresponding behavior. It can be a useful tool in situations where you have a large number of options and you want to avoid a long chain of if-else statements. Want to learn more about Python and practice Python programming? Explore related articles here.

 

__________________________________________________________________________

 

Recently completed any professional course/certification from the market? Tell us what you liked or disliked in the course for more curated content.

 

Click here to submit its review.

About the Author
author-image
Atul Harsha
Senior Manager Content
Experienced AI and Machine Learning content creator with a passion for using data to solve real-world challenges. I specialize in Python, SQL, NLP, and Data Visualization. My goal is to make data science engaging an Read Full Bio
qna

Comments