From ProgrammingExamples
Jump to: navigation, search

back to Python examples

In many languages, there is a switch or case statement. Python appears not to have that, so you will often see a lot of if/elif/elif/.../else blocks. There is a better way using a dict.
For concreteness, lets mimic this C code:

int count_of_bs = 0
switch(a) {
  case 'a': call_a(a); break;
  case 'b': ++count_of_bs; break
  default: call_other(a); break;

Here it is in Python (with function definitions and a few quick tests)

count_of_bs = 0
# these functions would have to be defined in any case.
def call_a(a):
  print 'a called with %s'%str(a)
def call_other(a):
  print 'otherwise, with %s'%str(a)
#this function is 'overhead' to make the switch statement work
def do_b(a):
  global count_of_bs
  count_of_bs += 1
# this is the declaration of the switch
switch = {
  'b': do_b,
# run some test cases. Note that we handle non-scalars just fine
print ('count_of_bs %s'%count_of_bs)
for tc in ['b', 'a','b','c','b','alphabet',(99,'bottles','beer'),'b']:
  # this is how you use it
print ('count_of_bs %s'%count_of_bs)
count_of_bs 0
a called with a
otherwise, with c
otherwise, with alphabet
otherwise, with (99, 'bottles', 'beer')
count_of_bs 4

back to Python examples