Created
July 13, 2019 19:53
-
-
Save serhii73/9ecfc15195f9f734d23277d47645b480 to your computer and use it in GitHub Desktop.
Dicts can be used to emulate switch/case statements
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def dispatch_if(operator, x, y): | |
if operator == 'add': | |
return x + y | |
elif operator == 'sub': | |
return x - y | |
elif operator == 'mul': | |
return x * y | |
elif operator == 'div': | |
return x / y | |
else: | |
return None | |
def dispatch_dict(operator, x, y): | |
return { | |
'add': lambda: x + y, | |
'sub': lambda: x - y, | |
'mul': lambda: x * y, | |
'div': lambda: x / y, | |
}.get(operator, lambda: None)() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment