0% found this document useful (0 votes)
65 views

Switch Case in Python (Replacement) - GeeksforGeeks

Uploaded by

jourvelitoua
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
65 views

Switch Case in Python (Replacement) - GeeksforGeeks

Uploaded by

jourvelitoua
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

12/17/24, 1:52 PM Switch Case in Python (Replacement) - GeeksforGeeks

Switch Case in Python (Replacement)


Last Updated : 25 Jul, 2024

In this article, we will try to understand Switch Case in Python (Replacement).

What is the replacement of Switch Case in Python?


Unlike every other programming language we have used before, Python does
not have a switch or case statement. To get around this fact, we use dictionary
mapping.

Method 1: Switch Case implement in Python using Dictionary Mapping

In Python, a dictionary is an unordered collection of data values that can be


used to store data values. Unlike other data types, which can only include a
single value per element, dictionaries can also contain a key: value pair.
The key value of the dictionary data type functions as cases in a switch
statement when we use the dictionary to replace the Switch case statement.

Python3

1 # Function to convert number into string


2 # Switcher is dictionary data type here
3 def numbers_to_strings(argument):
4 switcher = {
5 0: "zero",
6 1: "one",
7 2: "two",
8 }
9
10 # get() method of dictionary data type returns
11 # value of passed argument if it is present
12 # in dictionary otherwise second argument will
13 # be assigned as default value of passed argument
14 return switcher.get(argument, "nothing")
15

https://www.geeksforgeeks.org/switch-case-in-python-replacement/ 1/13
12/17/24, 1:52 PM Switch Case in Python (Replacement) - GeeksforGeeks

# Driver program
17 if __name__ == "__main__":
18 argument=0
19 print (numbers_to_strings(argument))

Output

zero

Method 2: Switch Case implement in Python using if-else

The if-else is another method to implement switch case replacement. It is used


to determine whether a specific statement or block of statements will be
performed or not, i.e., whether a block of statements will be executed if a
specific condition is true or not.

Python

1 bike = 'Yamaha'
2
3 if bike == 'Hero':
4 print("bike is Hero")
5
6 elif bike == "Suzuki":
7 print("bike is Suzuki")
8
9 elif bike == "Yamaha":
10 print("bike is Yamaha")
11
12 else:
13 print("Please choose correct answer")

Output

bike is Yamaha

Method 3: Switch Case implement in Python using Class


https://www.geeksforgeeks.org/switch-case-in-python-replacement/ 2/13
12/17/24, 1:52 PM Switch Case in Python (Replacement) - GeeksforGeeks

In this method, we are using a class to create a switch method inside the
python switch class in Python.

Python

1 class Python_Switch:
2 def day(self, month):
3
4 default = "Incorrect day"
5
6 return getattr(self, 'case_' + str(month), lambda:
default)()
7
8 def case_1(self):
9 return "Jan"
10
11 def case_2(self):
12 return "Feb"
13
14 def case_3(self):
15 return "Mar"
16
17
18 my_switch = Python_Switch()
19
20 print(my_switch.day(1))
21
22 print(my_switch.day(3))

Output
https://www.geeksforgeeks.org/switch-case-in-python-replacement/ 3/13
12/17/24, 1:52 PM Switch Case in Python (Replacement) - GeeksforGeeks

Jan
Mar

Switch Case in Python


In Python 3.10 and after that, Python will support this by using match in place
of switch:

Python

Python Basics # This


1Interview code
runs
Pythononly
Questions Quiz inPopular
python 3.10 or
Packages above
Python versions
Projects Practice Python AI Wit
2 def number_to_string(argument):
3 match argument:
4 case 0:
5 return "zero"
6 case 1:
7 return "one"
8 case 2:
9 return "two"
10 case default:
11 return "something"
12
13
14 head = number_to_string(2)
15 print(head)

It is similar to that of switch cases in C++, Java, etc.

Switch Case in Python (Replacement) – FAQs

How to Implement Switch-Case Functionality in Python?

Python does not have a built-in switch-case statement like some other
programming languages. However, you can achieve similar functionality
using alternatives such as dictionaries, if-elif-else chains, or the match-
case statement introduced in Python 3.10.

What Alternatives Exist for Switch-Case Statements in Python?

https://www.geeksforgeeks.org/switch-case-in-python-replacement/ 4/13
12/17/24, 1:52 PM Switch Case in Python (Replacement) - GeeksforGeeks

If-Elif-Else Chains:

value = 2

if value == 1:
result = "one"
elif value == 2:
result = "two"
elif value == 3:
result = "three"
else:
result = "unknown"

print(result) # Output: two

Dictionaries:

def one():
return "one"

def two():
return "two"

def three():
return "three"

switcher = {
1: one,
2: two,
3: three
}

value = 2
result = switcher.get(value, lambda: "unknown")()
print(result) # Output: two

Match-Case (Python 3.10+):

value = 2

match value:
case 1:
result = "one"
case 2:
result = "two"
case 3:
result = "three"
case _:
result = "unknown"
https://www.geeksforgeeks.org/switch-case-in-python-replacement/ 5/13
12/17/24, 1:52 PM Switch Case in Python (Replacement) - GeeksforGeeks

print(result) # Output: two

How is the Match-Case Statement Used in Python 3.10?

The match-case statement introduced in Python 3.10 provides a more


readable and efficient way to handle multiple conditions. It allows you to
match values against patterns.

Example:

value = 2

match value:
case 1:
result = "one"
case 2:
result = "two"
case 3:
result = "three"
case _:
result = "unknown"

print(result) # Output: two

How to Use Dictionaries as a Switch-Case Alternative in Python?

Dictionaries can be used to map keys to functions, providing a concise


and efficient switch-case alternative.

Example:

def one():
return "one"

def two():
return "two"

def three():
return "three"

switcher = {

https://www.geeksforgeeks.org/switch-case-in-python-replacement/ 6/13
12/17/24, 1:52 PM Switch Case in Python (Replacement) - GeeksforGeeks

1: one,
2: two,
3: three
}

value = 2
result = switcher.get(value, lambda: "unknown")()
print(result) # Output: two

Explanation:

Define functions for each case.


Use a dictionary to map each value to its corresponding function.
Use get method to retrieve the function, with a default lambda function
for unknown values.
Call the retrieved function.

What Are Advantages of Using Match-Case Over If-Else in Python?

1. Readability: The match-case syntax is more readable and concise


compared to multiple if-elif-else statements.

match value:
case 1:
result = "one"
case 2:
result = "two"
case _:
result = "unknown"

2. Pattern Matching: match-case supports complex pattern matching, not


just simple value matching.

point = (1, 2)

match point:
case (0, 0):
result = "Origin"
case (x, 0):
result = f"X-axis at {x}"
case (0, y):
result = f"Y-axis at {y}"

https://www.geeksforgeeks.org/switch-case-in-python-replacement/ 7/13
12/17/24, 1:52 PM Switch Case in Python (Replacement) - GeeksforGeeks

case (x, y):


result = f"Point at {x}, {y}"

3. Efficiency: The match-case statement can be more efficient, especially


with complex matching patterns.

4. Maintainability: With clear structure and reduced boilerplate, match-


case makes the code easier to maintain.

Looking to dive into the world of programming or sharpen your Python skills?
Our Master Python: Complete Beginner to Advanced Course is your ultimate
guide to becoming proficient in Python. This course covers everything you need
to build a solid foundation from fundamental programming concepts to
advanced techniques. With hands-on projects, real-world examples, and
expert guidance, you'll gain the confidence to tackle complex coding
challenges. Whether you're starting from scratch or aiming to enhance your
skills, this course is the perfect fit. Enroll now and master Python, the language
of the future!

Switch Case in Python

https://www.geeksforgeeks.org/switch-case-in-python-replacement/ 8/13
12/17/24, 1:52 PM Switch Case in Python (Replacement) - GeeksforGeeks

Comment More info Next Article


Alternatives to Case/Switch
Statements in Python

Similar Reads
Switch Case in Python (Replacement)
In this article, we will try to understand Switch Case in Python (Replacement). What is the replacement of
Switch Case in Python?Unlike every other programming language we have used before, Python does not hav…

5 min read

Alternatives to Case/Switch Statements in Python


In many programming languages, the case or switch statement is a control flow mechanism that allows a
variable to be tested for equality against a list of values, with each value associated with a block of code to b…

3 min read

Python | Pandas Series.replace()


Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a
hashable type. The object supports both integer- and label-based indexing and provides a host of methods…

3 min read

replace() in Python to replace a substring


Given a string str that may contain one more occurrences of “AB”. Replace all occurrences of “AB” with “C” in
str. Examples: Input : str = "helloABworld" Output : str = "helloCworld" Input : str = "fghABsdfABysu" Outpu…

1 min read

Switch case in R
Switch case statements are a substitute for long if statements that compare a variable to several integral
values. Switch case in R is a multiway branch statement. It allows a variable to be tested for equality against…

2 min read

How to replace a word in excel using Python?


Excel is a very useful tool where we can have the data in the format of rows and columns. We can say that
before the database comes into existence, excel played an important role in the storage of data. Nowadays…

3 min read

Copy And Replace Files in Python

https://www.geeksforgeeks.org/switch-case-in-python-replacement/ 9/13
12/17/24, 1:52 PM Switch Case in Python (Replacement) - GeeksforGeeks
In Python, copying and replacing files is a common task facilitated by modules like `shutil` and `os`. This
process involves copying a source file to a destination location while potentially replacing any existing file…

2 min read
Python String replace() Method
The replace() method replaces all occurrences of a specified substring in a string and returns a new string
without modifying the original string. Let’s look at a simple example of replace() method. [GFGTABS] Python…

2 min read

Python | Replace sublist with other in list


Sometimes, while working with Python, we can have a problem in which we need to manipulate a list in such
a way that we need to replace a sublist with another. This kind of problem is common in the web…

10 min read

Python DateTime - time.replace() Method with Example


In this article, we will discuss the time.replace() method in Python. This method is used to manipulate objects
of time class of module datetime. It is used to replace the time with the same value, except for those…

2 min read

Using Else Conditional Statement With For loop in Python


Using else conditional statement with for loop in python In most of the programming languages (C/C++, Java,
etc), the use of else statement has been restricted with the if conditional statements. But Python also allows…

2 min read

How to Replace Values in a List in Python?


In this article, we are going to see how to replace the value in a List using Python. We can replace values in
the list in serval ways. Below are the methods to replace values in the list. Using list indexingUsing for…

6 min read

Convert String to Set in Python


We can convert a string to setin Python using the set() function. Syntax : set(iterable) Parameters : Any
iterable sequence like list, tuple or dictionary. Returns : An empty set if no element is passed. Non-repeating…

2 min read

How to search and replace text in a file in Python ?


In this article, we will learn how we can replace text in a file using python. Method 1: Searching and replacing
text without using any external module Let see how we can search and replace text in a text file. First, we…

5 min read

Replacing strings with numbers in Python for Data Analysis

https://www.geeksforgeeks.org/switch-case-in-python-replacement/ 10/13
12/17/24, 1:52 PM Switch Case in Python (Replacement) - GeeksforGeeks
Sometimes we need to convert string values in a pandas dataframe to a unique integer so that the algorithms
can perform better. So we assign unique numeric value to a string value in Pandas DataFrame. Note: Before…

3 min read
Replacing column value of a CSV file in Python
Let us see how we can replace the column value of a CSV file in Python. CSV file is nothing but a comma-
delimited file. Method 1: Using Native Python way Using replace() method, we can replace easily a text into…

2 min read

Alphabet range in Python


When working with strings and characters in Python, you may need to create a sequence of letters, such as
the alphabet from 'a' to 'z' or 'A' to 'Z'. Python offers various options for accomplishing this, taking advantage…

3 min read

Pandas Replace Multiple Values in Python


Replacing multiple values in a Pandas DataFrame or Series is a common operation in data manipulation tasks.
Pandas provides several versatile methods for achieving this, allowing you to seamlessly replace specific…

5 min read

Numpy string operations | replace() function


In the numpy.core.defchararray.replace() function, each element in arr, return a copy of the string with all
occurrences of substring old replaced by new. Syntax : numpy.core.defchararray.replace(arr, old, new, count =…

1 min read

Article Tags : Python

Practice Tags : python

Corporate & Communications Address:-


A-143, 7th Floor, Sovereign Corporate
Tower, Sector- 136, Noida, Uttar Pradesh
(201305) | Registered Address:- K 061,
Tower K, Gulshan Vivante Apartment,
Sector 137, Noida, Gautam Buddh
Nagar, Uttar Pradesh, 201305

https://www.geeksforgeeks.org/switch-case-in-python-replacement/ 11/13
12/17/24, 1:52 PM Switch Case in Python (Replacement) - GeeksforGeeks

Company Languages
About Us Python
Legal Java
In Media C++
Contact Us PHP
Advertise with us GoLang
GFG Corporate Solution SQL
Placement Training Program R Language
GeeksforGeeks Community Android Tutorial
Tutorials Archive

DSA Data Science & ML


Data Structures Data Science With Python
Algorithms Data Science For Beginner
DSA for Beginners Machine Learning
Basic DSA Problems ML Maths
DSA Roadmap Data Visualisation
Top 100 DSA Interview Problems Pandas
DSA Roadmap by Sandeep Jain NumPy
All Cheat Sheets NLP
Deep Learning

Web Technologies Python Tutorial


HTML Python Programming Examples
CSS Python Projects
JavaScript Python Tkinter
TypeScript Web Scraping
ReactJS OpenCV Tutorial
NextJS Python Interview Question
Bootstrap Django
Web Design

Computer Science DevOps


Operating Systems Git
Computer Network Linux
Database Management System AWS
Software Engineering Docker
Digital Logic Design Kubernetes
Engineering Maths Azure
Software Development GCP
Software Testing DevOps Roadmap

https://www.geeksforgeeks.org/switch-case-in-python-replacement/ 12/13
12/17/24, 1:52 PM Switch Case in Python (Replacement) - GeeksforGeeks

System Design Inteview Preparation


High Level Design Competitive Programming
Low Level Design Top DS or Algo for CP
UML Diagrams Company-Wise Recruitment Process
Interview Guide Company-Wise Preparation
Design Patterns Aptitude Preparation
OOAD Puzzles
System Design Bootcamp
Interview Questions

School Subjects GeeksforGeeks Videos


Mathematics DSA
Physics Python
Chemistry Java
Biology C++
Social Science Web Development
English Grammar Data Science
Commerce CS Subjects
World GK

@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved

https://www.geeksforgeeks.org/switch-case-in-python-replacement/ 13/13

You might also like