<img alt="How to Implement Switch-Case in Python" data- data-src="https://kirelos.com/wp-content/uploads/2023/09/echo/How-to-Implement-Switch-Case-in-Python.jpg/w=800" data- decoding="async" height="420" src="data:image/svg xml,” width=”800″>
Want to implement a switch-case construct in Python? Learn the different approaches you can take to emulate switch-case behavior.
If you’ve programmed in C or JavaScript, you’ll have used the switch-case statement. But why do we need a switch-case construct?
Suppose you have a set of different actions (or code blocks). And which action you perform (the code block to execute) depends on the value of a variable or an expression.
Some examples include:
- Assigning grades to students based on their scores
- Choosing string manipulation techniques based on the user’s choice
- Performing arithmetic operations on two numbers depending on the user input
So the switch-case construct provides a convenient way to implement such logic. When you need to execute—based on the variable or expression’s value—one of the many possible actions.
While Python doesn’t have a built-in switch-case construct, there are several approaches you can use to achieve similar functionality. In this article, we’ll explore these approaches.
Emulating Switch-Case Behavior in Python
Let’s see how we can emulate switch-case behavior in Python by taking an example.
We’ll write a simple program that does the following:
- Sample a word, a Python string, at random from a list of words.
- Provide context and prompt the user. Define the string operations—string manipulation—to perform on the chosen word.
- Account for operations for case change (lowercase, uppercase, titlecase, and more) including a default behavior. Use built-in Python string methods as needed.
- Prompt the user for input. Because the input, by default, is a string, convert it to an int by type casting.
Python strings are immutable. So the string methods do not modify the original string. Rather they return a copy of the string with the required changes. Let’s review the Python string methods we’ll use:
String Method | Description |
---|---|
lower() |
Returns a copy of the string where all characters are in lower case |
upper() |
Returns a copy of the string where all characters are in upper case |
title() |
Returns a copy of the string formatted in title case |
swapcase() |
Returns a copy of the string where the lower and upper case characters are converted to upper and lowercase, respectively |
The following code snippet samples a word from word_list
at random and fetches user input:
import random
# List of words to choose from
word_list = ["Python", "programming", "Hello", "world", "context", "Switch"]
# Randomly select a word from the list
word = random.choice(word_list)
# Provide context and available options to the user
print("Welcome! You have a randomly selected word.")
print("Choose an option to manipulate the word:")
print("1. Lowercase")
print("2. Uppercase")
print("3. Titlecase")
print("4. Swapcase")
print("5. Default behavior")
# Get user option
option = int(input("Enter your option: "))
Here’s an example showing how the string ‘Python’ is modified based on the user’s choice:
When you now run the program, you should be prompted for the input like so:
Welcome! You have a randomly selected word.
Choose an option to manipulate the word:
1. Lowercase
2. Uppercase
3. Titlecase
4. Swapcase
5. Default behavior
Enter your option:
Next, let’s proceed to implement the different approaches.
Using If-Elif-Else Ladder
In this approach, we use a series of if-elif-else statements to check the user’s choice against predefined options. We then execute a corresponding block of code based on the user’s input.
# if-elif-else
if option == 1:
result = word.lower()
elif option == 2:
result = word.upper()
elif option == 3:
result = word.title()
elif option == 4:
result = word.swapcase()
else:
result = word
print(f"Your random word is {word} and the result is {result}")
Here:
- We compare the user’s input to each option using if-elif statements.
- When a match is found, we execute the corresponding code block.
- If none of the if-elif conditions match, we execute the else block for default behavior.
You can run the script now, enter the choice, and verify the output:
Welcome! You have a randomly selected word
Choose an option to manipulate the word:
1. Lowercase
2. Uppercase
3. Titlecase
4. Swapcase
5. Default behavior
Enter your option: 2
Your random word is Switch and the result is SWITCH.
The if-elif-else ladder is easy to implement. But it can be a challenge to maintain. In this example, we had five cases (including the default behavior). In practice, however, we may have many more cases. Such long if-elif-else ladders are a code smell you should avoid.
So let’s proceed to an implementation that’s maintainable.
Using Dictionary Mapping and First-Class Functions
You can leverage Python dictionaries and functions to emulate switch-case behavior.
📑 Python Functions Are First-Class Citizens
In Python, functions are first-class citizens. You can do much more than just defining and calling functions:
- Once you define a function, you can assign it to another variable, use functions as elements of lists, values in a dictionary, and much more.
- You can also pass them around: functions can be passed in as arguments to other functions and functions can return functions.
In this approach, we’ll use a dictionary to map user choices to corresponding functions or actions. This is a more efficient way to handle multiple choices, as it avoids a long chain of if-elif statements.
First, let’s define the following functions for the various string operations:
# Define functions for each option
def lower_case(word):
return word.lower()
def upper_case(word):
return word.upper()
def title_case(word):
return word.title()
def swap_case(word):
return word.swapcase()
Next, let’s do the following:
- Create a dictionary called
choices
where the keys are user choices, and values are functions or actions to perform. - Use the dictionary method
get()
to retrieve the selected action based on the user’s choice. If the choice is not found in the dictionary, we provide a default action specified by a lambda function. - Then execute the selected action on the random word.
# Store functions in a dictionary
options = {
1: lower_case,
2: upper_case,
3: title_case,
4: swap_case,
}
# Use the dictionary to select and call the appropriate function
result = options.get(option, lambda x: x)(word)
print(f"Your random word is {word} and the result is {result}")
Here’s a sample output:
Welcome! You have a randomly selected word.
Choose an option to manipulate the word:
1. Lowercase
2. Uppercase
3. Titlecase
4. Swapcase
5. Default behavior
Enter your option: 4
Your random word is Hello and the result is hELLO.
Using Match-Case
📝 Note: You need Python 3.10 or a later version to use match-case statements.
Starting from Python 3.10, you can use the match
statement to implement a switch-case-like construct. The match
statement with its simple syntax provides a more intuitive way to handle multiple cases. The _
(underscore) serves as the default case.
Here’s how we can re-write our example using match-case
:
- We use the
match
statement to compare the user’s input against various cases. - Each case specifies a choice and the code to execute if that choice matches.
- The
_
(underscore) serves as a default case, executing code when none of the other cases match.
match option:
case 1:
result = word.lower()
case 2:
result = word.upper()
case 3:
result = word.title()
case 4:
result = word.swapcase()
case _:
result = word # Default behavior, return the string as is
print(f"Your random word is {word} and the result is {result}.")
You can now run the script and verify the output:
Welcome! You have a randomly selected word.
Choose an option to manipulate the word:
1. Lowercase
2. Uppercase
3. Titlecase
4. Swapcase
5. Default behavior
Enter your option: 2
Your random word is world and the result is WORLD.
⚙ Though the
match
statement provides a convenient way to implement a switch-case construct, it’s intended for more helpful structural pattern matching tasks beyond emulating switch-case behavior.
Wrapping Up
Let’s summarize the different approaches to achieve switch-case functionality in Python:
- The if-elif-else ladder is easy to implement but is a pain to maintain. So use them minimally—only when you don’t have too many options to check for.
- You can leverage Python dictionaries and functions to emulate switch-case behavior. Include the different choices and the corresponding functions as the keys and values of the dictionary, respectively.
- The match-case statement, introduced in Python 3.10, helps implement this switch-case construct with a simple and intuitive syntax. However, the match-case statement is a great choice for more interesting structural pattern-matching use cases.
You can find the code examples for this tutorial on GitHub. If you’re preparing for coding interviews, check out this compilation of top Python interview questions.