Guide to Python’s Switch Case Statement
Introduction to Conditional Logic in Python
In programming, handling multiple conditional statements effectively is key to writing clean and maintainable code. Languages like C, Java, and Go achieve this through the switch-case
statement, which offers a structured way of handling different conditions.
However, Python initially relied on the if-elif-else construct for conditional logic, which can result in less readable code, especially when dealing with complex conditions.
In Python 3.10, the introduction of the match-case statement made handling conditional logic much more elegant, expressive, and Pythonic. The match-case statement helps improve code readability and maintainability, offering a more concise solution to the issues faced with if-elif-else
constructs.
With the if-elif-else
construct, conditions are checked in sequence. The first condition to evaluate as true
is executed. If no conditions evaluate to True
, the else
block is executed, if it exists.
Here’s the syntax demonstrating this logic:
if condition1:# Code to be executed if condition1 is Trueelif condition2:# Code to be executed if condition2 is Trueelif condition3:# Code to be executed if condition3 is Trueelse:# Code to execute if none of the above conditions are True
As an example, consider a scenario where we’re verifying user commands. We can use if-elif-else
to determine which action should be taken based on the input:
user_input = input("Enter a command: ")if user_input == "start":print("Starting the process.")elif user_input == "stop":print("Stopping the process.")elif user_input == "pause":print("Pausing the process.")else:print("Invalid command.")
Here, the program asks the user to “Enter a command.”
Depending on the user’s input, the code prints “start,” “stop,” or “pause.” If an input is not detected, the default message is “Invalid command.”
If the user enters the command start
the output will be:
Enter a command: startStarting the process.
Long chains of if-elif-else can become difficult to follow as complexity increases, reducing readability and making maintenance more challenging due to the need for widespread adjustments. Here’s where match-case
is helpful, offering a cleaner and more efficient way to handle scenarios like this.
Learn Python 3
Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today. Try it for freeUnderstanding the Syntax of Python match-case
Python’s match-case
statement was introduced in Python version 3.10, enabling clean and efficient handling of conditional logic. The match-case
statement replaces long if-elif-else
constructs and allows developers to match values or structures against a specific pattern using a _
wildcard for unmatched cases. This feature significantly improves code readability, maintainability, and versatility. Here’s the syntax to understand the match-case
statement in Python:
match expression:
case pattern1:
# Code block for pattern1
case pattern2:
# Code block for pattern2
case patternN:
# Code block for patternN
case _:
# Default code block (optional)
Key Components of match-case
:
match
: The starting point of the statement that evaluates a variable or expression and checks it against the patterns in thecase
blocks.case
: Defines a pattern to match the value, executing the corresponding code block if a match is found.Wildcard(
_)
: Thedefault
case handles unmatched patterns, similar to theelse
block inif-elif-else
.
The match-case
statement supports nesting, which means we can place match-case
statements within individual cases. This feature enables the handling of more complex and hierarchical logic, making it easier to manage intricate conditions while keeping the code clean and readable.
Here is an example that defines a function, process_command()
, that takes a command as input
and uses the match-case
statement to evaluate it.
def process_command(command):match command:case "start":print("Starting the process.")case "stop":print("Stopping the process.")case "pause":print("Pausing the process.")case _:print("Invalid command.")command = input("Enter a command: ")process_command(command)
- If the command is “
start
”, it prints “Starting the process.” - If the command is “
stop
”, it prints “Stopping the process.” - If the command is “
pause
” it prints “Pausing the process.” - If the command doesn’t match any of the predefined cases, the wildcard
_
is used to catch all the other commands, printing “Invalid command.”
When the user enters the command pause
at the prompt, the code produces the following output:
Enter a command: pausePausing the process.
Using Python match-case
statements with Constants
The simplest implementation of match-case
involves matching constants. Here’s an example that maps day_ numbers
to day_ names
:
def get_day_name(day_number):match day_number:case 1:return "Monday"case 2:return "Tuesday"case 3:return "Wednesday"case 4:return "Thursday"case 5:return "Friday"case 6:return "Saturday"case 7:return "Sunday"case _:return "Invalid day number"# Example usageprint(get_day_name(1))print(get_day_name(5))print(get_day_name(9))
The output of the get_day_name()
function is as follows:
- For day number
1
, the output is:Monday
- For day number
5
, the output is:Friday
- For day number
9
, the output is:Invalid day number
MondayFridayInvalid day number
Using Python match-case
Statement with the OR
Operator
In scenarios where handling multiple values individually results in repetitive code, the match-case
statement offers a concise and efficient solution. If developers encounter values that need the same treatment, they can group them in one case using the OR
operator (|
), making the code more efficient, streamlined, and readable.
Now, let’s apply this concept with an example where we classify days
of the week as weekdays
or weekends
using the match-case
statement and the OR
operator:
def get_day_type(day):match day:# Match weekdayscase "Monday" | "Tuesday" | "Wednesday" | "Thursday" | "Friday":return "Weekday"case "Saturday" | "Sunday":# Match weekendsreturn "Weekend"case _:# Default case for invalid inputreturn "Invalid day"# Example usageprint(get_day_type("Monday"))print(get_day_type("Sunday"))print(get_day_type("Holiday"))
The output will be:
WeekdayWeekendInvalid day
Applications of Python Switch Statement
The match-case
statement simplifies handling complex conditional logic in a way that is structured and readable. Such statements are exceptionally good for handling multiple conditions or data structures and are perfect for controlling multiple conditions or data structures, they can help manage decision trees.
Here are some key advantages of using the match-case
statement in Python to enhance code readability and efficiency:
- Controlling Multiple Conditions: When we deal with multiple conditions,
match-case
is a very concise and readable solution. It helps avoid long chains ofif-elif-else
, making the code easier to understand and maintain. - Handling Specific Patterns in Data Structures:
match-case
simplifies handling complex data structures like dictionaries, lists, and tuples by directly matching specific patterns, making the code cleaner and more efficient. - Simplifying Complex Decision Trees:
match-case
simplifies nested decision logic, especially for hierarchical conditions or scenarios with multiple patterns.
Limitations of Python Switch Statement
Although match-case
has many advantages, there are situations where it might not be the ideal solution:
- Performance on Large Datasets: For situations involving large datasets,
match-case
might not always be the optimal choice. Its sequential pattern evaluation can lead to performance bottlenecks, where traditional structures likeif-elif-else
or hash-based lookups (e.g., dictionaries) may perform better. - Not a universal fit: While
match-case
excels in handling structured and hierarchical data. For less complex scenarios,if-elif-else
constructs are often more concise and intuitive. - Readability Trade-Offs in Complex Patterns: Overly intricate or deeply nested patterns in
match-case
can reduce readability, especially for developers who are unfamiliar with this construct.
Following these best practices and keeping its limitations in mind, we can make good use of Python’s match-case
statement. Although it does enhance the readability and structure of code, proper usage is necessary.
Conclusion
In this article, we explored the modern and structured way of using Python’s match-case
statement and how it handles conditional logic. We walked through its syntax, key components, and some practical applications that illustrate how it makes complicated decision-making easier and improves code readability by using pattern matching effectively. match-case
provides a versatile tool for managing various scenarios, from handling data structures to replacing traditional if-elif-else
chains.
For further insights into Python programming and advanced techniques, explore Codecademy’s Learn intermediate Python 3 course.
'The Codecademy Team, composed of experienced educators and tech experts, is dedicated to making tech skills accessible to all. We empower learners worldwide with expert-reviewed content that develops and enhances the technical skills needed to advance and succeed in their careers.'
Meet the full teamRelated articles
- Article
JavaScript Switch Case vs If-Else Statement: When to Use Each
Learn when to use the JavaScript `switch` case and `if-else` statement for better code readability and efficiency. Make the right choice for your next project! - Article
How to Use the CASE Statement in SQL (With Examples)
Learn how to use the SQL `CASE` statement to implement conditional logic efficiently. Explore its syntax, use cases, best practices, and performance considerations. - Article
Conditional Statements
Use this article as a reference sheet for JavaScript conditional statements.
Learn more on Codecademy
- Course
Learn Python 3
Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.With CertificateBeginner Friendly23 hours - Free course
Python for Programmers
An introduction to the basic syntax and fundamentals of Python for experienced programmers.Intermediate3 hours - Course
Learn the Command Line
Learn about the command line, starting with navigating and manipulating the file system, and ending with redirection and configuring the environment.With CertificateBeginner Friendly4 hours