python中有没有switch_python 中无switch(写了几个函数代替switch)

字典的常用用途之一代替switch

在C/C++/Java语言中,有个很方便的函数switch,比如:

复制代码代码如下:

public class test {

public static void main(String[] args) {

String s = "C";

switch (s){

case "A":

System.out.println("A");

break;

case "B":

System.out.println("B");

break;

case "C":

System.out.println("C");

break;

default:

System.out.println("D");

}

}

}

在Python中要实现同样的功能,

方法一,就是用if, else语句来实现,比如:

from __future__ import division

def add(x, y):

return x + y

def sub(x, y):

return x - y

def mul(x, y):

return x * y

def div(x, y):

return x / y

def operator(x, y, sep='+'):

if   sep == '+': print add(x, y)

elif sep == '-': print sub(x, y)

elif sep == '*': print mul(x, y)

elif sep == '/': print div(x, y)

else: print 'Something Wrong'

print __name__

if __name__ == '__main__':

x = int(raw_input("Enter the 1st number: "))

y = int(raw_input("Enter the 2nd number: "))

s = raw_input("Enter operation here(+ - * /): ")

operator(x, y, s)

方法二,用字典来巧妙实现同样的switch的功能,比如:

复制代码代码如下:

#coding=gbk

from __future__ import division

x = int(raw_input("Enter the 1st number: "))

y = int(raw_input("Enter the 2nd number: "))

def operator(o):

dict_oper = {

'+': lambda x, y: x + y,

'-': lambda x, y: x - y,

'*': lambda x, y: x * y,

'/': lambda x, y: x / y}

return dict_oper.get(o)(x, y)

if __name__ == '__main__':

o = raw_input("Enter operation here(+ - * /): ")

print operator(o)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值