Python - Estructura de Control Switch
Caso 1
def switch_demo(x):
switcher = {
1: lambda: print("uno"),
2: lambda: print("dos"),
3: lambda: print("tres")
}
switcher.get(x, lambda: print("default"))()
switch_demo(1) # Output: uno
switch_demo(4) # Output: default
Caso 2
def greet(name):
switcher = {
"John": lambda: print("Hello, John!"),
"Jane": lambda: print("Hello, Jane!"),
"default": lambda: print("Hello, stranger!")
}
switcher.get(name, switcher["default"])()
greet("John") # Output: Hello, John!
greet("Bob") # Output: Hello, stranger!
Caso 3
def get_day_of_week(day):
switcher = {
1: lambda: "Monday",
2: lambda: "Tuesday",
3: lambda: "Wednesday",
4: lambda: "Thursday",
5: lambda: "Friday",
6: lambda: "Saturday",
7: lambda: "Sunday"
}
return switcher.get(day, lambda: "Invalid day")()
print(get_day_of_week(3)) # Output: Wednesday
print(get_day_of_week(8)) # Output: Invalid day
Caso 4
def get_month_name(month):
switcher = {
1: lambda: "January",
2: lambda: "February",
3: lambda: "March",
4: lambda: "April",
5: lambda: "May",
6: lambda: "June",
7: lambda: "July",
8: lambda: "August",
9: lambda: "September",
10: lambda: "October",
11: lambda: "November",
12: lambda: "December"
}
return switcher.get(month, lambda: "Invalid month")()
print(get_month_name(6)) # Output: June
print(get_month_name(13)) # Output: Invalid month
Caso 5
def get_color_name(color_code):
switcher = {
"R": lambda: "Red",
"G": lambda: "Green",
"B": lambda: "Blue",
"Y": lambda: "Yellow"
}
return switcher.get(color_code, lambda: "Unknown color")()
print(get_color_name("R")) # Output: Red
print(get_color_name("X")) # Output: Unknown color
Case 6
def get_currency_symbol(currency):
switcher = {
"USD": lambda: "{{SSR}}quot;,
"EUR": lambda: "€",
"GBP": lambda: "£"
}
return switcher.get(currency, lambda: "Unknown currency")()
print(get_currency_symbol("USD")) # Output: $
print(get_currency_symbol("JPY")) # Output: Unknown currency
Caso 7
def get_planet_name(planet_id):
switcher = {
1: lambda: "Mercury",
2: lambda: "Venus",
3: lambda: "Earth",
4: lambda: "Mars",
5: lambda: "Jupiter",
6: lambda: "Saturn",
7: lambda: "Uranus",
8: lambda: "Neptune"
}
return switcher.get(planet_id, lambda: "Unknown planet")()
print(get_planet_name(3)) # Output: Earth
print(get_planet_name(9)) # Output: Unknown planet