huygn / til

Today I Learned
MIT License
2 stars 0 forks source link

Python switch-case #12

Open huygn opened 8 years ago

huygn commented 8 years ago

Other languages’ switch-case feature is not exist in the Python world, we can either using if/elif block or using dictionary:

def numbers_to_strings(argument):
     return {
          0: "zero",
          1: "one",
          2: "two"
     }.get(argument, "nothing")

Ref:

cab-1729 commented 4 years ago

if you want to emulate switch cases just like other languages in python then instead of using the dictionary to return values , return functions . Or even better , if you don't want to define separate functions for all the cases use the exec func and execute the strings , what I mean is this: exec( {
1:'print("case 1")', 2:'print("case 2")'

}.get(args,'print("Default case")') )