Python’s unique approach to the switch-case statement
While many other programming languages, like Java, offer built-in switch-case syntax, Python takes a different approach. Although Python doesn’t have a direct switch-case construct, there are multiple ways to simulate this behavior.

Python has no switch statement. Other languages have one, so you will look for it. There are three good ways to do the same job in Python.

Methods to Implement Switch-Case in Python

Using If-Else Chains

The if-else construct in Python can replicate the functionality of a switch-case. In Python, the “else if” statement is shortened to elif, making the code more concise. Here’s a simple example demonstrating this:

user_cmd = input("Please enter your choice:\n")
if user_cmd == "select":
ops = "select"
elif user_cmd == "update":
ops = "update"
elif user_cmd == "delete":
ops = "delete"
elif user_cmd == "insert":
ops = "insert"
else:
ops = "invalid choice!"
print(ops)

Python Switch Case Example

Using Dictionaries

In Python, dictionaries can be a powerful tool to mimic the switch-case statement. This method involves using the dict.get(key, default=None) function. Here’s how you can achieve switch-case behavior with dictionaries:

user_cmd = input("Please enter your choice:\n")
operations = {
'select': 'select action',
'update': 'update action',
'delete': 'delete action',
'insert': 'insert action'
}
default_choice = 'invalid choice!'
ops = operations.get(user_cmd, default_choice)
print(ops)

Combining Lambda Functions with Dictionaries

Lambda functions provide a way to create small anonymous functions. By pairing a lambda function with a dictionary, you can further simulate the switch-case behavior in Python. Here’s an example of this technique:

user_cmd = input("Please enter your choice:\n")
operations = {
'select': lambda: "select action",
'update': lambda: "update action",
'delete': lambda: "delete action",
'insert': lambda: "insert action"
}
ops = operations.get(user_cmd, lambda: "invalid choice!")
print(ops())

Three ways

  • if and elif. Works in every Python version. Keep it flat and it stays readable.
  • match (Python 3.10 and up). Real switch, it matches values and patterns. It is the cleanest one now.
  • A dictionary of functions. Good when each branch does something different, and you can look up the key.

With a dictionary you can check if the key exists before you call it, which stops a KeyError on bad input. Reach for if and elif unless you have many branches or you are on 3.10 or later.

The fastest way to learn this is to write it yourself. The PyChallenge exercises run in your browser, no install needed.