• Skip to main content
  • Skip to primary sidebar
  • Skip to secondary sidebar
  • Skip to footer

Computer Notes

Library
    • Computer Fundamental
    • Computer Memory
    • DBMS Tutorial
    • Operating System
    • Computer Networking
    • C Programming
    • C++ Programming
    • Java Programming
    • C# Programming
    • SQL Tutorial
    • Management Tutorial
    • Computer Graphics
    • Compiler Design
    • Style Sheet
    • JavaScript Tutorial
    • Html Tutorial
    • Wordpress Tutorial
    • Python Tutorial
    • PHP Tutorial
    • JSP Tutorial
    • AngularJS Tutorial
    • Data Structures
    • E Commerce Tutorial
    • Visual Basic
    • Structs2 Tutorial
    • Digital Electronics
    • Internet Terms
    • Servlet Tutorial
    • Software Engineering
    • Interviews Questions
    • Basic Terms
    • Troubleshooting
Menu

Header Right

Home » Python » Switch Case in Python
Next →
← Prev

Switch Case in Python

By Dinesh Thakur

The Switch-Case statement is an important decision-making programming feature that is widely used in modular programming, enabling you to execute different blocks of code based on a variable value during runtime. Unlike many other languages, Python does not directly support switch or a case statement.

The reason for this is, instead of sequentially analyzing each statement, it evaluates the expression or variable and jumps explicitly to the following branch code to execute.

This tutorial explains Python’s built-in ways like a dictionary, lambda function, and classes to create custom Python switch-case statements.

Note: If you want to know why Python does not have a switch case, please refer to the PEP 3103 description.

We’ll be covering the following topics in this tutorial:

  • Switch Case using a Dictionary
  • Switch Case using a Class
  • Switch Case using Python functions

Switch Case using a Dictionary

An efficient dictionary mapping, also known as associative arrays, is a pythonic way of implementing a switch-statement that offers one-to-one key-value mappings. Follow the below steps.

1.First, creating separate function for each case and make sure there is a default case to handling function.

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 "Invalid day"

2. Next, build a dictionary object(It store key-value pair in the memory) and save each function.

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

3 Write a switch() function that accepts the day of the week as an argument.

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

4 Switch() calls the get() method on the dictionary object, which returns and concurrently invokes function that match the argument.

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

Example: 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 "Invalid 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
Invalid day

Here when we pass an argument to the switch function, the switcher’s dictionary mapping is scanned. The associated value is printed if a match is found. Otherwise, a default string ('Invalid day') is printed. The default string helps to implement the switch 'default case.'

Switch Case using a Class

Python classes may also be used as an alternate way to execute switch-case statements. Let’s use an example to do so.

• First, There is a switch class, which specifies the switch() method.
• The day of the week is an argument, it is converted to a string, and it is appended to the 'case_ ' literal. The resulting string is then passed to the getattr() function.
• The getattr() method returns the matching function of the type.
• If the string doesn’t find a match, getattr() returns the default lambda function.

# Implement Python Switch Case Statement using Class
class Switch:
   def switch(self, dayOfWeek):
       default = "Invalid 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 = Switch()
print(s.switch(1))
print(s.switch(0))

The output is as follows:

Monday
Invalid day

Switch Case using Python functions

The Python dictionary values may be of any data. Therefore, we don’t have to use constants (integers, strings). Function names and lambdas may also be used as values.

E.g., by building a dictionary of function names as values, we can also implement this switch statement. It is convenient to use with the Python switch case statement. We have a few steps to consider.

• First, for each case, specify the individual functions.
• Make sure there is a default case handling function.
• First, create a dictionary object and store each of the functions.
• After that, write a switch() function that accepts the number of months as arguments.
• The switch() calls a get() method on a dictionary object that returns and concurrently calls a function matching the argument.
In this case, a switcher is a function names dictionary without strings.

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 switch(dayOfWeek):
switcher = {
    1: monday,
    2: tuesday,
    3: wednesday,
    4: thursday,
    5: friday,
    6: saturday,
    7: sunday
}
    func = switcher.get(dayOfWeek, lambda: "Invalid day")
    print func()

You’ll also like:

  1. Switch Case in C
  2. Switch ….Case Statement
  3. is a default case necessary in a switch statement
  4. Write a C++ Program to detect whether the entered number is even or odd. Use nested switch () case statement.
  5. Write a java program changing the case of a string(Lower case)
Next →
← Prev
Like/Subscribe us for latest updates     

About Dinesh Thakur
Dinesh ThakurDinesh Thakur holds an B.C.A, MCDBA, MCSD certifications. Dinesh authors the hugely popular Computer Notes blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps.

Dinesh Thakur is a Freelance Writer who helps different clients from all over the globe. Dinesh has written over 500+ blogs, 30+ eBooks, and 10000+ Posts for all types of clients.


For any type of query or something that you think is missing, please feel free to Contact us.


Primary Sidebar

Python

Python Tutorials

  • Python - Home
  • Python - Features
  • Python - Installation
  • Python - Hello World
  • Python - Operators Types
  • Python - Data Types
  • Python - Variable Type
  • Python - Switch Case
  • Python - Line Structure
  • Python - String Variables
  • Python - Condition Statement
  • Python - if else Statement
  • Python - for-loop
  • Python - while loop
  • Python - Command Line
  • Python - Regular Expression

Python Collections Data Types

  • Python - List
  • Python - Sets
  • Python - Tuples
  • Python - Dictionary

Python Functions

  • Python - Functions
  • Python - String Functions
  • Python - Lambda Function
  • Python - map() Function

Python Object Oriented

  • Python - Oops Concepts
  • Python - File Handling
  • Python - Exception Handling
  • Python - Multithreading
  • Python - File I/O

Python Data Structure

  • Python - Linked List
  • Python - Bubble Sort
  • Python - Selection Sort
  • Python - Linear Search
  • Python - Binary Search

Python Programs

  • Python - Armstrong Number
  • Python - Leap Year Program
  • Python - Fibonacci Series
  • Python - Factorial Program

Other Links

  • Python - PDF Version

Footer

Basic Course

  • Computer Fundamental
  • Computer Networking
  • Operating System
  • Database System
  • Computer Graphics
  • Management System
  • Software Engineering
  • Digital Electronics
  • Electronic Commerce
  • Compiler Design
  • Troubleshooting

Programming

  • Java Programming
  • Structured Query (SQL)
  • C Programming
  • C++ Programming
  • Visual Basic
  • Data Structures
  • Struts 2
  • Java Servlet
  • C# Programming
  • Basic Terms
  • Interviews

World Wide Web

  • Internet
  • Java Script
  • HTML Language
  • Cascading Style Sheet
  • Java Server Pages
  • Wordpress
  • PHP
  • Python Tutorial
  • AngularJS
  • Troubleshooting

 About Us |  Contact Us |  FAQ

Dinesh Thakur is a Technology Columinist and founder of Computer Notes.

Copyright © 2023. All Rights Reserved.