5.python语法基础-switch结构

说明:
    1.switch比if...else的语句表达更清晰,可读性更高
    2.python没有提供switch语句
    3.pthon中使用字典来实现switch语句的功能,实现方法分2步:
        a.定义一个字典;b.调用字典的get()获取相应表达式
python代码:
  1. def add(x,y):
  2. return x+y
  3. def sub(x,y):
  4. return x-y
  5. def mul(x,y):
  6. return x*y
  7. def div(x,y):
  8. return x/y
  9. operation={'+':add,'-':sub,'*':mul,'/':div} #用字典方法存不同类型运算符
  10. def result(x,o,y):
  11. print operation.get(o)(x,y) #使用get(o)等价于字典中的操作符+-*/对应的键值value即函数
  12. result(10, '-', 3) #调用函数,验证结果,在中间传什么操作符做什么操作,比起if来程序效率高
    注意:使用字典方式处理的switch语句比起if...else处理少了前面多个层次判断的处理,程序效率提高了




posted on 2015-08-26 22:53  georgetest  阅读(438)  评论(0编辑  收藏  举报

导航