TechBeamersTechBeamers
  • Learn ProgrammingLearn Programming
    • Python Programming
      • Python Basic
      • Python OOP
      • Python Pandas
      • Python PIP
      • Python Advanced
      • Python Selenium
    • Python Examples
    • Selenium Tutorials
      • Selenium with Java
      • Selenium with Python
    • Software Testing Tutorials
    • Java Programming
      • Java Basic
      • Java Flow Control
      • Java OOP
    • C Programming
    • Linux Commands
    • MySQL Commands
    • Agile in Software
    • AngularJS Guides
    • Android Tutorials
  • Interview PrepInterview Prep
    • SQL Interview Questions
    • Testing Interview Q&A
    • Python Interview Q&A
    • Selenium Interview Q&A
    • C Sharp Interview Q&A
    • PHP Interview Questions
    • Java Interview Questions
    • Web Development Q&A
  • Self AssessmentSelf Assessment
    • Python Test
    • Java Online Test
    • Selenium Quiz
    • Testing Quiz
    • HTML CSS Quiz
    • Shell Script Test
    • C/C++ Coding Test
Search
  • Python Multiline String
  • Python Multiline Comment
  • Python Iterate String
  • Python Dictionary
  • Python Lists
  • Python List Contains
  • Page Object Model
  • TestNG Annotations
  • Python Function Quiz
  • Python String Quiz
  • Python OOP Test
  • Java Spring Test
  • Java Collection Quiz
  • JavaScript Skill Test
  • Selenium Skill Test
  • Selenium Python Quiz
  • Shell Scripting Test
  • Latest Python Q&A
  • CSharp Coding Q&A
  • SQL Query Question
  • Top Selenium Q&A
  • Top QA Questions
  • Latest Testing Q&A
  • REST API Questions
  • Linux Interview Q&A
  • Shell Script Questions
© 2024 TechBeamers. All Rights Reserved.
Reading: Python Switch Case Statement Explained
Font ResizerAa
TechBeamersTechBeamers
Font ResizerAa
  • Python
  • SQL
  • C
  • Java
  • Testing
  • Selenium
  • Agile Concepts Simplified
  • Linux
  • MySQL
  • Python Quizzes
  • Java Quiz
  • Testing Quiz
  • Shell Script Quiz
  • WebDev Interview
  • Python Basic
  • Python Examples
  • Python Advanced
  • Python OOP
  • Python Selenium
  • General Tech
Search
  • Programming Tutorials
    • Python Tutorial
    • Python Examples
    • Java Tutorial
    • C Tutorial
    • MySQL Tutorial
    • Selenium Tutorial
    • Testing Tutorial
  • Top Interview Q&A
    • SQL Interview
    • Web Dev Interview
  • Best Coding Quiz
    • Python Quizzes
    • Java Quiz
    • Testing Quiz
    • ShellScript Quiz
Follow US
© 2024 TechBeamers. All Rights Reserved.
Python BasicPython Tutorials

Python Switch Case Statement Explained

Python does not have a built-in switch case statement, but there are a few different ways to implement it. Let's check out.
Last updated: Nov 05, 2023 6:44 pm
By Meenakshi Agarwal
Share
5 Min Read
Implement Python Switch Case Statement
Implement Python Switch Case Statement
SHARE

Switch case is a powerful decision-making construct commonly used in modular programming. In this tutorial, we’ll explain multiple ways to implement the Python switch case statement. When you don’t want a conditional block cluttered with multiple if conditions, then, switch case can give a cleaner way to implement control flow in your program.

Contents
A Typical Switch Case in C ProgrammingSwitch Case using a DictionarySwitch Case using a Class

Python Switch Case Statement

Unlike other programming languages, Python doesn’t provide a switch case instrument over the self.

However, it has many other constructs like a Python dictionary, Python lambda function, and Python classes to write a custom implementation of the Python switch case statement.

If you are keen to know why Python doesn’t have a switch case, then refer to the explanation about PEP 3103.

Before diving into this further, let’s have a quick view of the most common example of a switch case statement in the C programming language.

A Typical Switch Case in C Programming

  • The switch case in C is one of the decision-making statements. You can only pass an integer or enum value to the C switch-case statement.
  • Unlike the if…else block which requires evaluating expressions in each condition, the switch has a single point of interaction which leads to different paths of execution.
  • A switch is a control instruction that decides the control to flow based on the value of a variable or an expression.

In the below example, the variable ‘dayOfWeek’ is a constant integer variable that represents days in a week. And, the switch-case block prints the name of the day based on its value.

    switch (dayOfWeek) {
    case 1:
        printf("%s", Monday);
        break;
    case 2:
        printf("%s", Tuesday);
        break;
    case 3:
        printf("%s", Wednesday);
        break;
    case 4:
        printf("%s", Thursday);
        break;
    case 5:
        printf("%s", Friday);
        break;
    case 6:
        printf("%s", Saturday);
        break;
    case 7:
        printf("%s", Sunday);
        break;
    default:
        printf("Incorrect day");
        break;
    }

There are a couple of facts to consider for the switch-case statement.

  • The expression under the switch gets evaluated once.
  • It should result in a constant integer value. [Note: In Python, we can alter this behavior.]
  • A case with a duplicate value should not appear.
  • If no case matches, then the default case gets executed.

Implement Python Switch Case Statement

In Python, we can make a switch case statement in one of the following ways. However, please remember that there is no limit to innovation. You could devise your own way to do it.

Switch Case using a Dictionary

It is simple to use a dictionary for implementing the Python switch case statement. Follow the below steps.

  • First, define individual functions for every case.
  • Make sure there is a function/method to handle the default case.
  • Next, make a dictionary object and store each of the functions beginning with the 0th index.
  • After that, write a switch() function accepting the day of the week as an argument.
  • The switch() calls the get() method on the dictionary object which returns the function matching the argument and invokes it simultaneously.
# Implement Python Switch Case Statement using Dictionary

def monday():
    return "monday"
def tuesday():
    return "tuesday"
def wednesday():
    return "wednesday"
def thursday():
    return "thursday"
def friday():
    return "friday"
def saturday():
    return "saturday"
def sunday():
    return "sunday"
def default():
    return "Incorrect day"

switcher = {
    1: monday,
    2: tuesday,
    3: wednesday,
    4: thursday,
    5: friday,
    6: saturday,
    7: sunday
    }

def switch(dayOfWeek):
    return switcher.get(dayOfWeek, default)()

print(switch(1))
print(switch(0))

The output is as follows:

Monday
Incorrect day

Switch Case using a Class

It is quite easy to use a class for implementing the Python switch case statement. Let’s do it with an example.

  • In the below example, there is a PythonSwitch class that defines the switch() method.
  • It takes the day of the week as an argument, converts it to string, and appends it to the ‘case_’ literal. After that, the resultant string gets passed to the getattr() method.
  • getattr() returns a matching function available in the class.
  • If the string doesn’t find a match, then the getattr() returns the lambda function as default.
  • The class also has the definition for functions specific to different cases.
# Implement Python Switch Case Statement using Class

class PythonSwitch:

    def switch(self, dayOfWeek):
        default = "Incorrect day"
        return getattr(self, 'case_' + str(dayOfWeek), lambda: default)()

    def case_1(self):
        return "Monday"
 
    def case_2(self):
        return "Tuesday"
 
    def case_3(self):
        return "Wednesday"

s = PythonSwitch()

print(s.switch(1))
print(s.switch(0))

The output is as follows:

Monday
Incorrect day

You Might Also Like

How to Connect to PostgreSQL in Python

Generate Random IP Address (IPv4/IPv6) in Python

Python Remove Elements from a List

How to Use Extent Report in Python

10 Python Tricky Coding Exercises

Meenakshi Agarwal Avatar
By Meenakshi Agarwal
Follow:
Hi, I'm Meenakshi Agarwal. I have a Bachelor's degree in Computer Science and a Master's degree in Computer Applications. After spending over a decade in large MNCs, I gained extensive experience in programming, coding, software development, testing, and automation. Now, I share my knowledge through tutorials, quizzes, and interview questions on Python, Java, Selenium, SQL, and C# on my blog, TechBeamers.com.
Previous Article Python Format How To Format Data Types In Python Python String Format
Next Article Python Program to Insert a Key-Value Pair to the Dictionary Insert a Key-Value Pair to the Dictionary

Popular Tutorials

SQL Interview Questions List
50 SQL Practice Questions for Good Results in Interview
SQL Interview Nov 01, 2016
Demo Websites You Need to Practice Selenium
7 Sites to Practice Selenium for Free in 2024
Selenium Tutorial Feb 08, 2016
SQL Exercises with Sample Table and Demo Data
SQL Exercises – Complex Queries
SQL Interview May 10, 2020
Java Coding Questions for Software Testers
15 Java Coding Questions for Testers
Selenium Tutorial Jun 17, 2016
30 Quick Python Programming Questions On List, Tuple & Dictionary
30 Python Programming Questions On List, Tuple, and Dictionary
Python Basic Python Tutorials Oct 07, 2016
//
Our tutorials are written by real people who’ve put in the time to research and test thoroughly. Whether you’re a beginner or a pro, our tutorials will guide you through everything you need to learn a programming language.

Top Coding Tips

  • PYTHON TIPS
  • PANDAS TIPSNew
  • DATA ANALYSIS TIPS
  • SELENIUM TIPS
  • C CODING TIPS
  • GDB DEBUG TIPS
  • SQL TIPS & TRICKS

Top Tutorials

  • PYTHON TUTORIAL FOR BEGINNERS
  • SELENIUM WEBDRIVER TUTORIAL
  • SELENIUM PYTHON TUTORIAL
  • SELENIUM DEMO WEBSITESHot
  • TESTNG TUTORIALS FOR BEGINNERS
  • PYTHON MULTITHREADING TUTORIAL
  • JAVA MULTITHREADING TUTORIAL

Sign Up for Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

Loading
TechBeamersTechBeamers
Follow US
© 2024 TechBeamers. All Rights Reserved.
  • About
  • Contact
  • Disclaimer
  • Privacy Policy
  • Terms of Use
TechBeamers Newsletter - Subscribe for Latest Updates
Join Us!

Subscribe to our newsletter and never miss the latest tech tutorials, quizzes, and tips.

Loading
Zero spam, Unsubscribe at any time.
x