pytho本身并未提供switch语句,但可以通过dict来模拟switch,

#方法1
def add(x,y):
    return x+y

def dec(x,y):
    return x-y

def multi(x,y):
    return x*y

def div(x,y):
    return x/y

operater = {'+':add,'-':dec,'*':multi,'/':div}
def calculator(x,o,y):
    return operater.get(o)(x,y)

#方法2
def calculator1(x,o,y):
    return {'+':x+y,'-':x-y,'*':x*y,'/':x/y}.get(o)

def test():
    print calculator(2, '*', 6)
    print calculator1(2,'+',6)
if __name__ == "__main__":
    test()

方法二每次调用时都需要生成dict。

相关文章:

  • 2022-12-23
  • 2021-12-08
  • 2022-12-23
  • 2022-12-23
  • 2021-06-26
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-02-06
  • 2021-10-10
  • 2022-12-23
  • 2021-12-22
  • 2021-12-17
  • 2021-09-02
相关资源
相似解决方案