How to Implement Case/Switch Statements in Python?

Barbara Streisand
Release: 2024-11-18 11:22:02
Original
750 people have browsed it

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"
Copy after login

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]()
Copy after login

The above is the detailed content of How to Implement Case/Switch Statements in Python?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template