Python switch case
<p>I am trying to use dictionary as switch case on python, however, the parameter does not seem to be pass to the called function, please help:</p>

<pre><code>def switchcase(num,cc):
    def fa(num):
        out= num*1.1;
    def fb(num):
        out= num*2.2;
    def fc(num):
        out= num*3.3;
    def fd(num):
        out= num*4.4;
    options = {
        "a":fa(num),
        "b":fb(num),
        "c":fc(num),
        "d":fd(num)
        } 
    out=0
    options[cc];
    return out
print switchcase(10,"a")
</code></pre>

<p>the output is 0, I could not figure out the problem</p>

<p>The problem is:</p>

<pre><code>out=0
options[cc];
return out
</code></pre>

<p>Basically -- no matter what <code>options[cc]</code> gives you, you're going to return <code>0</code> because that's the value of <code>out</code>.  Note that setting <code>out</code> in the various <code>fa</code>, <code>fb</code>, ... functions does <em>not</em> change the value of <code>out</code> in the caller.</p>

<p>You probably want:</p>

<pre><code>def switchcase(num,cc):
    def fa(num):
        return num*1.1;
    def fb(num):
        return num*2.2;
    def fc(num):
        return num*3.3;
    def fd(num):
        return num*4.4;
    options = {
        "a":fa(num),
        "b":fb(num),
        "c":fc(num),
        "d":fd(num)
        } 
    return options[cc];
</code></pre>

<p>Also note that this will be horribly inefficient in practice.  You're creating 4 functions (and calling each) every time you call <code>switchcase</code>.</p>

<p>I'm guessing that you actually want to create a pre-made map of functions.  Then you can pick up the function that you actually want from the map and call it with the given number:</p>

<pre><code>def fa(num):
    return num*1.1

def fb(num):
    return num*2.2

def fc(num):
    return num*3.3

def fd(num):
    return num*4.4

OPTIONS = {
    "a":fa,
    "b":fb,
    "c":fc,
    "d":fd
} 

def switchcase(num,cc):
    return OPTIONS[cc](num)
</code></pre>

python switch-statement