While there is no built-in switch-case statement in Python programming like in Java, you can achieve the same in certain ways.
Example 1: Using dictionary
def switch_case(case):
switch = {
1: "Case 1",
2: "Case 2",
3: "Case 3"
}
return switch.get(case, "Invalid case option!")
# Example usage:
print(switch_case(1))
print(switch_case(2))
print(switch_case(3))
# Invalid
print(switch_case(4))
You can also call a function based on the case match.
Example 2: With Functionsdef switch_case(case):
switch = {
1: func1,
2: func2,
}
func = switch.get(case, lambda: print("Invalid case option!"))
return func()
def func1():
print("func 1!")
def func2():
print("func 2!")
# Example usage:
switch_case(1)
switch_case(2)
switch_case(3)
Now let's make use of the default case when there is no match.
Example 3: Default case
def switch_case(case):
switch = {
1: func1
}
func = switch.get(case, default_case)
return func()
def func1():
print("func 1!")
def default_case():
print("Default case!")
# Example usage:
switch_case(1)
switch_case(2)
If you are using Python 3.10 or above you can make use of the pattern matching to implement switch-case.
Example 4: Pattern Matching (Python 3.10)def calculator(num1, num2, operator):
match operator:
case '+':
return num1 + num2
case '-':
return num1 - num2
case '*':
return num1 * num2
case '/':
if num2 != 0:
return num1 / num2
else:
return "Error: Cannot divide by zero"
case _:
return "Error: Invalid operator!"
print("---- Switch Case Based Calculator ----")
num1 = float(input("Enter 1st number: "))
num2 = float(input("Enter 2nd number: "))
operator = input("Enter the operator (+, -, *, /): ")
result = calculator(num1, num2, operator)
print("Result:", result)
---- Switch Case Based Calculator ----
Enter 1st number: 10
Enter 2nd number: 20
Enter the operator (+, -, *, /): *
Result: 200.0
Facing issues? Have Questions? Post them here! I am happy to answer!
Author Info:
Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.
Follow him on: X
You can also reach out to him via e-mail: rakesh@code2care.org
More Posts related to Python,
- How to convert int to ASCII in Python
- How to make use of SQLite Module in Python?
- Split a String into Sub-string and Parse in Python
- Python: Pandas Rename Columns with List Example
- How to run Python file from Mac Terminal
- How to Exit a Loop in Python Code
- Python: How to Plot a Histogram using Matplotlib and data as list
- MD5 Hashing in Python
- Jupyter: Safari Cant Connect to the Server localhost:8888/tree
- Fix: AttributeError: str object has no attribute decode. Did you mean: encode?[Python]
- How to Read a binary File with Python
- How to add two float numbers in Python
- Python: How to install YAML Package
- Python: How to Save Image from URL
- What is Markdown in Jupyter Notebook with Examples
- How to change the Python Default version
- 33: Python Program to send an email vid GMail
- How to comment code in Python
- How to Fix AttributeError in Python
- Fix: error: Jupyter command `jupyter-nbconvert` not found [VSCode]
- How to comment out a block of code in Python
- List of All 35 Reserved Keywords in Python Programming Language 3.11
- Import Other Python Files Examples
- Python: How to add Progress Bar in Console with Examples
- 3 Ways to convert bytes to String in Python
More Posts:
- How to run React Native App using Android Studio Emulator - Android-Studio
- Write to a File using Java Stream API - Java
- Android Studio: Cannot perform refactoring operation - Android-Studio
- Fix: cd: string not in pwd - zsh
- PowerShell: Steps to Connect to connect to Exchange Online - Powershell
- Error:The SDK Build Tools revision (XX.X.X) is too low for project. Minimum required is XX.X.X - Android
- Fix: Error creating bean with name securityConfig: Unsatisfied dependency expressed - NoSuchBeanDefinitionException: No qualifying bean of type - Java
- How do I run HTML file in Notepad? (Windows) - NotepadPlusPlus