python 基础学习 switch 语
switch 语法结构:
switch 语句用于编写多分支结构的程序,类似于if...elif...eles语句。
swtch 语句的表达的分支结果比if...elif...lese 语句表达的更清晰,代码的可读性更高。
####python并没有提供switch语句######
但是:Python 可以通过字典实现switch语句的功能。
实现方法:
定义一个字典
调用字典的get()获取相应的表达式
范例:
>>> 6/4
1
>>> 6.0/4
1.5
>>> from __future__ import division
>>> 5/2
2.5
# __future__模块 division 精确的除法
下面是一个计算器:
#!/usr/bin/python
#coding:utf-8
from __future__ import division
def jia(x,y):
return x+y
def jian(x,y):
return x-y
def chu(x,y):
return x/y
def cheng(x,y):
return x*y
def operator(x,o,y):
x =int(raw_input("plese somthing number:"))
y =int(raw_input("plese somthing number:"))
o = raw_input("plese somthing +/*-:")
if o == '+':
print jia(x,y)
elif o == '*':
print cheng(x,y)
elif o == '/':
print chu(x,y)
elif o == '-':
print jian(x,y)
else:
pass
print operator('x','o','y')
#注意三次判断是多余的,且如果符号错误,执行为空,效率不是很好
如果通过switch编写一个计算器
[root@zabbix tools]# cat switch.py
#!/usr/bin/python
#coding:utf-8
from __future__ import division
def jia(x,y):
return x+y
def jian(x,y):
return x-y
def chu(x,y):
return x/y
def cheng(x,y):
return x*y
operator = {"+":jia,"-":jian,"*":cheng,"/":chu}
print jia(2,4)
print jia
print operator["+"](3,4) #通过字典取值,省去判断的环节;
[root@zabbix tools]# python switch.py
6
<function jia at 0x7fc3ecb8fa28>
7
如果字典中没有值或值是错误的:print operator["("](3,4)
报错如:Traceback (most recent call last):
File "switch.py", line 20, in <module>
print operator["("](3,4)
KeyError: '('
所以我们可以使用字典中get的方法:
Traceback (most recent call last): print operator.get["-"](3,4)
File "switch.py", line 21, in <module>
print operator.get["-"](3,4)
TypeError: 'builtin_function_or_method' object is unsubscriptable
实现和if相同的操作:
[root@zabbix tools]# cat switch.py
#!/usr/bin/python
#coding:utf-8
from __future__ import division
def jia(x,y):
return x+y
def jian(x,y):
return x-y
def chu(x,y):
return x/y
def cheng(x,y):
return x*y
operator = {"+":jia,"-":jian,"*":cheng,"/":chu}
def f(x,o,y):
print operator.get(o)(x,y) #将字典中的key带入函数中,类似如if的判断
f(2,"-",4)
[root@zabbix tools]# python switch.py
-2
相关文章