4.7实现分支结构

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 jia
SyntaxError: 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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值