Python - Estructura de Control Switch

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

Information: Python - Estructura de Control Switch