Applying the "or" Pattern in Practice
The "or" pattern in Python "switch-case" statements can be applied in a variety of practical scenarios. Here are a few examples to illustrate its usage:
Suppose you have a program that prompts the user to enter a choice, and you need to perform different actions based on the user's input. You can use the "or" pattern to handle this scenario:
user_choice = input("Enter 'start', 'stop', or 'restart': ")
if user_choice in ('start', 'begin', 'run'):
## Start the process
print("Starting the process...")
elif user_choice in ('stop', 'end', 'quit'):
## Stop the process
print("Stopping the process...")
elif user_choice in ('restart', 'reset'):
## Restart the process
print("Restarting the process...")
else:
print("Invalid choice. Please try again.")
In this example, the user's input is compared against multiple options using the "or" pattern, and the corresponding action is performed.
Mapping Values to Actions
Another common use case for the "or" pattern is mapping values to specific actions or outcomes. For example, you might have a program that needs to perform different operations based on the type of file being processed:
file_extension = "txt"
if file_extension in ('.txt', '.doc', '.docx'):
## Process text-based files
print("Processing text-based file.")
elif file_extension in ('.jpg', '.png', '.gif'):
## Process image files
print("Processing image file.")
elif file_extension in ('.mp3', '.wav', '.ogg'):
## Process audio files
print("Processing audio file.")
else:
print("Unsupported file type.")
In this case, the "or" pattern is used to map file extensions to the appropriate file processing logic.
Handling Error Conditions
The "or" pattern can also be useful for handling error conditions and providing meaningful feedback to the user. For example, you might have a function that performs a calculation, and you want to handle various types of input errors:
def divide(a, b):
if b in (0, 0.0):
return "Error: Division by zero."
elif not isinstance(a, (int, float)) or not isinstance(b, (int, float)):
return "Error: Invalid input. Both arguments must be numbers."
else:
return a / b
print(divide(10, 2)) ## Output: 5.0
print(divide(10, 0)) ## Output: Error: Division by zero.
print(divide(10, "2")) ## Output: Error: Invalid input. Both arguments must be numbers.
In this example, the "or" pattern is used to check for the specific error conditions (division by zero and non-numeric input) and return appropriate error messages.
By applying the "or" pattern in these practical scenarios, you can create concise and readable Python code that handles a variety of use cases effectively.