Vera123 Vera123 - 2 months ago 14
Python Question

Python switch case

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:

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")


the output is 0, I could not figure out the problem

Answer

The problem is:

out=0
options[cc];
return out

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

You probably want:

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];

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

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:

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)