Skip to content

Python Switch Case – A Comprehensive Guide

What is Python Switch Statement? Learn Switch Case in Python - cover image

The switch case statement simplifies the decision-making process in programming by offering a more organized way to handle multiple conditions compared to Python’s if, elif, and else structure.

In Python, the if statement runs code if a condition is true, otherwise it runs code under else. Multiple conditions can be handled with elif statements. However, this approach can become cumbersome and confusing with numerous elif conditions and indentation levels. This is where the switch case statement provides a cleaner alternative.

What is a Switch Case Statement?

Switch case statements, found in many other programming languages, offer a more structured way to handle scenarios where multiple comparisons are required to make a decision. They allow us to branch execution to different parts of the code based on the value of an expression, providing a cleaner alternative to lengthy if-elif-else chains.

Flowchart: Switch Case

The flow chart above illustrates the workings of a switch case statement.

  • The switch case expression is evaluated once.
  • The value of the evaluated expression is compared with each case.
  • If a match is found the corresponding statement (or block of code) is executed – End Switch.
  • If no match is found, the default statement gets executed – End Switch.

Switch Case is a selection control statement. Also known as a conditional control statement, these statements direct the flow of execution based on whether certain conditions are true or false. It evaluates conditions and executes different blocks of code depending on the outcome.

Although Python lacks traditional switch case statements, it introduces similar functionality with the match and case statements starting from Python 3.10. Let’s learn about it in more detail.

Python’s Match and Case

Syntax

1. match Statement:
The match statement is used to start pattern matching on a variable. It examines the value of the variable against various patterns defined in the subsequent case statements.

match variable:
    # Pattern matching cases here

2. case Statement:
Each case specifies a pattern to match against the variable’s value. The code block following the case is executed if the pattern matches. You can use guards (additional conditions) with case statements to refine the matching criteria.

match variable:
    case pattern:
        # Code to execute if pattern matches

3. Using Guards:
Guards are conditional expressions that can be used in case statements to add extra conditions to the match.

match variable:    
    case _ if condition:
        # Code to execute if condition is true

The underscore can be used for two purposes:

  1. Wildcard Pattern: The underscore _ is used as a wildcard pattern that matches any value. It acts as a catch-all for values that do not match other specific patterns defined in the case statements.

2. Guard Conditions: When used with a guard (if condition), the underscore in case _ if condition: means that any value is acceptable as long as the condition specified in the guard is true. This allows additional conditions to be applied to the match process.

Example

def evaluate_number(n):
    match n:
        case 1:
            print("Number is one.")
        case 2:
            print("Number is two.")
        case _ if n < 0:
            print("Number is negative.")
        case _ if n % 2 == 0:
            print("Number is even.")
        case _:
            print("Number is odd and positive.")

evaluate_number(4)  # Output: Number is even.
  1. case 1: Matches if n is exactly.
  2. case 2: Matches if n is exactly.
  3. case _ if n < 0: Matches any value of n if it is less than 0. Here, _ indicates that the specific value is not important as long as the condition n < 0 is true.
  4. case _ if n % 2 == 0: Matches any value of n if it is an even number. The underscore _ is used here to indicate that any value can be matched as long as it satisfies the condition n % 2 == 0.
  5. case _: Acts as a default case that catches any value not matched by the previous case statements.

Code Implementation

The match statement allows for pattern matching, where you can check a variable against multiple patterns. Each case within the match block specifies a pattern to compare with the variable’s value, enabling clear and concise branching logic.

This concept can be more clearly illustrated with an example that converts a basic if, elif, and else structure into a match and case structure.

def determine_age_group(age):
    if age < 0:
        return "Invalid age"
    elif age <= 12:
        return "Child"
    elif age <= 19:
        return "Teenager"
    elif age <= 64:
        return "Adult"
    else:
        return "Senior"

print(determine_age_group(25))  # Output: Adult

Explanation: The determine_age_group() function categorizes a person’s age into life stages. It checks if the age is invalid (less than 0), or falls into specific ranges: “Child” (0-12), “Teenager” (13-19), “Adult” (20-64), or “Senior” (65 and older). For the input 25, it matches the “Adult” category and returns “Adult”, which is then printed.

In the matchcase version, we use pattern matching with guard conditions (using if within the case statements) to handle the different age ranges and special cases. This provides a similar logical structure to the if, elif, and else approach but leverages the new pattern matching capabilities introduced in Python 3.10.

def determine_age_group(age):
    match age:
        case _ if age < 0:
            return "Invalid age"
        case age if age <= 12:
            return "Child"
        case age if age <= 19:
            return "Teenager"
        case age if age <= 64:
            return "Adult"
        case _:
            return "Senior"

print(determine_age_group(25))  # Output: Adult

Explanation: The determine_age_group() function utilizes Python’s match and case statements to categorize a person’s age.

  • It begins with the match age: statement, which initiates the pattern matching process for age.
  • The function then evaluates a series of case statements. If the case is true, the subsequent code block, a return statement in this example, is executed.
  • The cases match ages falling within specific ranges: age<0 for “Invalid age”, age<=12 for “Child”, age<=19 for “Teenager”, and age<=64 for “Adult”. The final case, case _:, acts as a default catch-all for ages above 64, returning “Senior”.
  • When determine_age_group(25) is called, the function matches the age<=64 case, thus returning “Adult”, which is then printed.

Conclusion

Python uses match and case statements to imitate the functionality of a Switch Case statement. It offers a more organized alternative to if, elif, and else for handling multiple conditions. This approach simplifies complex decision-making and improves code readability, making it a valuable tool for Python developers.

Python is also crucial in the context of blockchain development. Its versatility and powerful libraries make it a good choice for building and interacting with blockchain systems. To understand why Python is so effective for blockchain projects, check out our article, 7 Reasons Why You Should Develop a Blockchain Using Python which explores the numerous advantages of using Python for blockchain development.

Related Reading:

FAQs

What is the purpose of Python’s match and case statements?

Python’s match and case statements provide a way to perform pattern matching, allowing developers to execute code blocks based on the structure and content of data. This feature offers a more readable and organized approach to handling multiple conditions compared to traditional if, elif, and else statements.

How do match and case differ from if-elif-else statements?

While if-elif-else statements evaluate boolean expressions to control program flow, match and case statements enable structural pattern matching, allowing for more complex and expressive condition handling. This distinction makes match-case particularly useful for scenarios involving intricate data structures.

Can match-case statements replace all if-elif-else scenarios?

No, match-case statements are best suited for situations requiring pattern matching and may not be appropriate for all conditional logic. Simple conditions can still be effectively handled using if-elif-else statements.

What are some practical applications of match-case statements in Python?

Match-case statements are particularly useful for parsing complex data structures, implementing state machines, and handling multiple input scenarios where pattern matching enhances code clarity and maintainability.