Difference between revisions of "Python/DictAsSwitch"
From ProgrammingExamples
< Python
(create example) |
m (format) |
||
Line 1: | Line 1: | ||
[[Python|<font size='-2'>''back to Python examples''</font>]] | [[Python|<font size='-2'>''back to Python examples''</font>]] | ||
---- | ---- | ||
− | In many languages, there is a switch or case statement. Python appears not to have that, so you will see a lot of if/elif/elif/.../else . There is a better way using a dict.<br /> | + | In many languages, there is a switch or case statement. Python appears not to have that, so you will often see a lot of <code>if/elif/elif/.../else</code> blocks. There is a better way using a dict.<br /> |
For concreteness, lets mimic this C code: | For concreteness, lets mimic this C code: | ||
<syntaxhighlight lang="c"> | <syntaxhighlight lang="c"> |
Latest revision as of 00:13, 29 June 2010
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)
switchExample.py
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 = { 'a':call_a, '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 switch.get(tc,call_other)(tc) print ('count_of_bs %s'%count_of_bs) """Output: count_of_bs 0 a called with a otherwise, with c otherwise, with alphabet otherwise, with (99, 'bottles', 'beer') count_of_bs 4 """