Skip to content Skip to sidebar Skip to footer

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)

Solution 1:

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)

Solution 2:

Here is an alternative take. You can just navigate to the necessary methods you have outside the switcher, and also pass optional arguments if you need:

def fa(num):
    return num*1.1
def fb(num):
    return num*2.2
def fc(num):
    return num*3.3
def fd(num, option=1):
    return num*4.4*option
def f_default(num):
    return num

def switchcase(cc):
    return {
        "a":fa,
        "b":fb,
        "c":fc,
        "d":fd,
    }.get(cc, f_default)

print switchcase("a")(10)  # for Python 3 --> print(switchcase("a")(10))
print switchcase("d")(10, 3)  # for Python 3 --> print(switchcase("d")(10, 3))

print(switchcase("a")(10))

11.0

print(switchcase("d")(10, 3))

132.0

print(switchcase("ddd")(10))

10


Solution 3:

Another shorter version would be:

def switchcase(num, cc):
    return {
        "a": lambda: num * 1.1,
        "b": lambda: num * 2.2,
        "c": lambda: num * 3.3,
        "d": lambda: num * 4.4,
        }.get(cc, lambda: None)()

print (switchcase(10,"a"))

Post a Comment for "Python Switch Case"