python中case的用法_Python Switch Case三种实现方法代码实例

Python没有switch语句,只能通过模拟来对应实现:

方法一:使用dictionary

**values = {

value1: do_some_stuff1,

value2: do_some_stuff2,

...

valueN: do_some_stuffN,

}

values.get(var, do_default_stuff)()

根据需求可以自行更改参数内容,灵活运用

def add(x,y):

print x+y

def minus(x,y):

print x-y

def multiply(x,y):

print x*y

def div(x,y):

print x/y

def fun_case_list(key,arg1,arg2):

operator = {

'+':add,

'-':minus,

'*':multiply,

'/':div

}

if operator.has_key(key):

return operator.get(key)(arg1,arg2)

else:

return 'No [%s] case in dic'%key #or do other func

if __name__ == "__main__":

fun_case_list('*',3,5)

fun_c

你可能感兴趣的:(python中case的用法)