Home > Article > Backend Development > 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]()
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!