"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Implement Case/Switch Statements in Python?

How to Implement Case/Switch Statements in Python?

Posted on 2025-02-26
Browse:839

How to Implement Case/Switch Statements in Python?

Python Equivalent to the Case/Switch Statement

Python does not provide a dedicated syntax for case/switch statements like other programming languages. However, there are several alternative approaches to achieve similar functionality.

Using Pattern Matching (Python 3.10 and above)

From version 3.10 onwards, Python introduced pattern matching. It allows you to match different patterns and execute corresponding code blocks.

def http_error(status):
    match status:
        case 400:
            return "Bad request"
        case 404:
            return "Not found"
        case 418:
            return "I'm a teapot"
        case _:  # Default case
            return "Something's wrong with the internet"

Using Dictionaries for Earlier Python Versions

Before Python 3.10, one common workaround is to use dictionaries to map input values to corresponding function blocks.

# Define the function blocks
def zero():
    print("You typed zero.\n")

def sqr():
    print("n is a perfect square\n")

def even():
    print("n is an even number\n")

def prime():
    print("n is a prime number\n")

# Map inputs to the function blocks
options = {0: zero,
           1: sqr,
           4: sqr,
           9: sqr,
           2: even,
           3: prime,
           5: prime,
           7: prime}

# Invoke the equivalent switch block
options[num]()
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3