4.7实现分支结构

来源:互联网 发布:中国每年出生人口数据 编辑:程序博客网 时间:2024/05/17 03:06
4.7实现分支结构
python 并没有提供swith语句
可以通过函数和定义字典实现switch语句功能
Step1:定义一个字典g;
step2:调用字典的get() 获取相应的表达式。
形式为:
{1:case1,2:case2}.get(x,lambda:*arg,**key:)()
>>> 5/2>>> 2#定义模块实现>>> from __future__ import division>>> 5/2>>> 2.5#python3.3.3 默认加载改模块from __future__ import division>>> 5/2>>> 2.5
example4.7.1
#if..elif实现简单计算器例子>>> from __future__ import division>>> def jia(x,y):return(x + y)>>> def jian(x,y):return(x - y)>>> def cheng(x,y):return(x*y)>>> def chu(x,y):return x/y>>> def operator(x,o,y):if o == "+":print (jia(x,y)))elif o == "-":print (jian(x,y))elif o == "*":print (cheng(x,y))elif o == "-":print (chu(x,y))else:pass>>> 开始执行operator>>> operator(2,'+',4)6>>> operator(3,'*',520)1560>>> operator(1990,'*',08)SyntaxError: invalid token>>> operator(1990,'*',8)15920>>> operator(8,'-',15)-7>>> 

##通过函数和定义字典实现switch语句功能

example4.7.2

##通过函数和定义字典实现简单计算器例子>>> def jia(x,y):return(x + y)>>> def jian(x,y):return(x - y)>>> def cheng(x,y):return(x*y)>>> def chu(x,y):return x/y>>> print jiaSyntaxError: invalid syntax>>> print(jia)<function jia at 0x020876A8>#定义一个字典>>> operator = {'+':jia,'-':jian,'*':cheng,'/':chu}>>> print(operator['+'])<function jia at 0x020876A8>>>> print(operator['/'])<function chu at 0x02087618>>>> ##相同的实现>>> print(jia)<function jia at 0x020876A8>>>> print(operator['+'])<function jia at 0x020876A8>>>> print(jia(5,20))25>>> print(operator['+'](5,20))25>>> print(operator[*](5,20))SyntaxError: invalid syntax>>> print(operator['*'](8,15))120>>> ### 引入get()>>> operator['%'](3,2)Traceback (most recent call last):  File "<pyshell#73>", line 1, in <module>    operator['%'](3,2)KeyError: '%'>>> operator.get('%')(3,2)Traceback (most recent call last):  File "<pyshell#74>", line 1, in <module>    operator.get('%')(3,2)TypeError: 'NoneType' object is not callable>>> 
#python中通过定义字典,调用字典中的get()获取相应的表达式
example4.7.3

>>> def jia(x,y):return(x + y)>>> def jian(x,y):return(x - y)>>> def cheng(x,y):return(x*y)>>> def chu(x,y):return x/y>>> operator = {'+':jia,'-':jian,'*':cheng,'/':chu}>>> def f(x,o,y):print(operator.get(o)(x,y))>>> f(8,"*",15)120

通过函数和定义字典实现switch功能:
{1:case1,2:case2}.get(x,lambda:*arg,**key:)()
example4.7.4

简化代码

>>> x = 1>>> y = 2>>> operator ='/'>>> result={}>>> result ={"+":x+y,"-":x-y,"*":x*y,"/":x/y}>>> print(result.get(operator))0.5>>> 

注:学习内容来源于网易云课堂《疯狂的Python:快速入门精讲》;代码执行环境为Win;Python版本为 3.3.3


0 0
原创粉丝点击