Introduction
The switch statement is a powerful and convenient tool for controlling the flow of your program. It allows you to quickly and easily create multiple branches of code, depending on the value of a given variable or expression. It's commonly used when you need to execute different logic depending on a given variable's value, which can have more than 2 (but a finite number) of values.
In this article, we will explore how to use the switch statement in Python and discuss its advantages over other control structures. Whether you are new to Python or an experienced developer, the switch statement can help you write cleaner, more efficient code.
Before v3.10
Before the Python switch statement was natively available in the language, programmers had to use other control structures to achieve the same functionality. One common approach was to use a series of if-else statements, with each branch of code being associated with a different value of the variable being tested.
For example, consider the following code:
value = "foo"
if value == "foo":
print("foo was selected")
elif value == "bar":
print("bar was selected")
else:
print("Nothing valid was selected")
In this code, we are using an if-else statement to determine which branch of code to execute based on the value of the variable value
. If value
is equal to "foo", the first branch of code will be executed. If value
is equal to "bar", the second branch of code will be executed. Otherwise, the code in the else
block will be executed.
While this approach works, it can quickly become unwieldy as the number of possible values for the variable increases. In addition, it can make the code difficult to read and understand.
Another approach that can be used to create a switch-like statement in Python is to use a dictionary. In this approach, the keys of the dictionary are the possible values of the variable being tested, and the values are the corresponding branches of code.
For example, consider the following code:
value = "foo"
switch = {
"foo": lambda: print("foo was selected"),
"bar": lambda: print("bar was selected"),
"default": lambda: print("Nothing valid was selected"),
}
switch.get(value, "default")()
In this code, we have defined a dictionary called switch
, with keys representing the possible values of the variable value
. For each key, we have assigned a lambda function as the value, which contains the corresponding branch of code. To execute the appropriate branch of code, we use the get()
method of the dictionary, which allows us to specify a default value to use if the given key does not exist in the dictionary.
While this approach is more flexible and compact than using if-else statements, it can still be difficult to read and understand, especially if the code in each branch is complex. In addition, it requires the use of lambda functions, which can be confusing for some programmers. We don't suggest using this method unless for some reason you can't use the other methods in this article.
With the introduction of the Python switch statement in Python v3.10, programmers now have a more convenient and intuitive way to control the flow of their programs based on the value of a given variable or expression. In the next section, we will explore how to use an actual switch statement in Python.
The match
/case
Statement (after v3.10)
After Python v3.10, the switch statement is handled using the match
keyword. This keyword is used to create a pattern-matching expression, which allows you to test the value of a given variable or expression against a series of patterns. If a match is found, the corresponding branch of code is executed.
For example, consider the following code:
value = "foo"
match value:
case "foo":
print("foo was selected")
case "bar":
print("bar was selected")
case _:
print("Nothing valid was selected")
Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!
In this code, we are using the match
keyword to create a pattern-matching expression, which tests the value of the variable value
against a series of patterns. If value
is equal to "foo", the first branch of code will be executed. If value
is equal to "bar", the second branch of code will be executed. Otherwise, the code in the else block will be executed.
Fall-through
One of the key differences between switch statements in Python and traditional switch statements in other languages is that Python's match
statement does not support fall-through. In other words, once a match is found and the corresponding branch of code is executed, the match
expression ends and no other code in the match
statement is executed. In other languages, this is usually achieved using the break
keyword, which is not needed or supported here.
If you want to achieve the same behavior as fall-through in a traditional switch statement, you can use the |
operator to match multiple cases. This operator allows you to specify multiple patterns in a single case
, and any of the patterns can be matched to trigger the execution of that branch.
For example, consider the following code:
value = "y"
match value:
case "yes" | "y":
print("The user confirmed")
case _:
print("The user denied")
Here, if the value of value
is equal to "yes" or "y", the first branch of code will be executed. This is equivalent to the fall-through behavior in a traditional switch statement.
Defaults
As you've probably noticed from the above examples, the "default" case is handled using an underscore (_
). This is considered the "wildcard" and matches all values. If one of the previous cases matches the value, then the default code branch is skipped over and not executed.
Conclusion
As you can see, the Python match (aka "switch") statement offers a powerful and convenient way to control the flow of your program. Whether you are new to Python or an experienced developer, the switch statement can help you write cleaner, more efficient code.