Skip to content

Instantly share code, notes, and snippets.

@netskink
Last active June 5, 2020 03:00
Show Gist options
  • Save netskink/059e16cc6832ec4678b8b8a4e90da6ee to your computer and use it in GitHub Desktop.
Save netskink/059e16cc6832ec4678b8b8a4e90da6ee to your computer and use it in GitHub Desktop.
switch implemented with a dictionary
def one():
return "this is function one"
def two():
return "this is function two"
def three():
return "this is function three"
def demo(argument):
switcher = {
1: one,
2: two,
3: three
}
# Get the function from the switcher dictionary
# Two bits of python capability here
# 1. Lambda
# lambda is small anonymous function.
#
# Example:
# return lambda a, b: a+b
#
# 2. dictionary get method
# Similar to some_dict[a_key], returns a default value if key is not found.
#
# Example:
# some_dict.get(a_key, default_value)
#
func = switcher.get(argument, lambda: "Invalid argument")
# execute the function
print(func())
demo(1)
demo(2)
demo(3)
demo(4)
def one(a_param):
print("This is function one")
print("This is a parameter {}" . format(a_param))
return
def two(a_param):
print("This is function two")
print("This is a parameter {}" . format(a_param))
return
def three(a_param):
print("This is function three")
print("This is a parameter {}" . format(a_param))
return
def demo(argument):
switcher = {
1: one,
2: two,
3: three
}
# Get the function from the switcher dictionary
# Two bits of python capability here
# 1. Lambda
# lambda is small anonymous function.
#
# Example:
# return lambda a, b: a+b
#
# 2. dictionary get method
# Similar to some_dict[a_key], returns a default value if key is not found.
#
# Example:
# some_dict.get(a_key, default_value)
#
a_param = "123"
func = switcher.get(argument, lambda x: print("Invalid argument " + x) )
# execute the function
func(a_param)
demo(1)
demo(2)
demo(3)
demo(4)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment