Skip to content

Instantly share code, notes, and snippets.

@sabinem
Created March 2, 2018 17:19
Show Gist options
  • Select an option

  • Save sabinem/05f24fda6909b7ea78d22b771a6bf402 to your computer and use it in GitHub Desktop.

Select an option

Save sabinem/05f24fda6909b7ea78d22b771a6bf402 to your computer and use it in GitHub Desktop.
case switch in python
# Once in a while you really would need case switching: this is how to best do it in python:
def positive_handler(x):
print("the number {} is positive".format(x))
def zero_handler(x):
print("the number {} is zero".format(x))
def negative_handler(x):
print("the number {} is negative".format(x))
options = {
'positive' : positive_handler,
'zero' : zero_handler,
'negative' : negative_handler
}
def cond_negative(x):
return x < 0
def cond_zero(x):
return x == 0
def cond_positive(x):
return x > 0
def decide(x):
if cond_positive(x):
options['positive'](x)
elif cond_zero(x):
options['zero'](x)
elif cond_negative(x):
options['negative'](x)
decide(-1)
decide(0)
decide(3)
return x < 0
def cond_1(x):
return x == 0
def cond_2(x):
return x > 0
def decide(x):
if cond_1():
options['case0']()
elif cond_2():
options['case1']()
elif cond_3():
options['case2']()
decide(-1)
decide(0)
decide(3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment