Python分支结构(switch)操作简介
作者:powerpoint_2016 时间:2021-07-05 07:24:46
Python当中并无switch语句,本文研究的主要是通过字典实现switch语句的功能,具体如下。
switch语句用于编写多分支结构的程序,类似与if….elif….else语句。
switch语句表达的分支结构比if…elif…else语句表达的更清晰,代码的可读性更高
但是python并没有提供switch语句。
python可以通过字典实现switch语句的功能,实现方法分为两步:
首先,定义一个字典
其次,调用字典的get()获取相应的表达式。
计算器:
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(2,'/',4)
用字典来实现switch操作
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
operator={"+":jia,"-":jian,"*":cheng,"/":chu}
print(operator["+"](3,2)) #operator["+"]等同于jia
print (jia(3,2)) #operator["+"](3,2)等同于jia(3,2)
运行结果:
5
5
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
operator={"+":jia,"-":jian,"*":cheng,"/":chu}
def f(x,o,y):
p=operator.get(o)(x,y)
print(p)
f(15,'/',5)
来源:http://blog.csdn.net/m0_38066258/article/details/77415674
标签:python,switch,case
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
2003年至今网页尺寸增长3倍
2008-04-29 19:27:00
![](https://img.aspxhome.com/file/UploadPic/20084/29/growth-average-web-page-sm_23s.gif)
Python人脸检测实战之疲劳检测
2021-02-23 16:31:37
![](https://img.aspxhome.com/file/2023/6/76716_0s.jpg)
python jinjia2的项目使用
2021-03-16 04:57:21
css:小技巧大问题,cellSpacing用css样式代替方法,其它样式类似解决!
2009-10-04 20:35:00
python接口自动化之ConfigParser配置文件的使用详解
2023-09-07 02:56:04
![](https://img.aspxhome.com/file/2023/2/92332_0s.png)
Python 开发工具通过 agent 代理使用的方法
2022-10-19 05:15:31
三种SQL分页查询的存储过程代码
2012-01-05 19:31:32
一些建站常用简单html代码
2008-06-01 13:17:00
Python利用keras接口实现深度神经网络回归
2021-02-07 12:01:41
![](https://img.aspxhome.com/file/2023/1/69581_0s.png)
Python实现批量转换文件编码的方法
2023-06-02 20:03:49
SQL 统计一个数据库中所有表记录的数量
2012-01-29 18:21:36
Python 操作Excel-openpyxl模块用法实例
2021-01-20 09:29:34
基于python图像处理API的使用示例
2022-12-19 02:14:53
ASP+JAVAScript:复杂表单的动态生成与验证
2007-10-06 21:51:00
解决pytorch报错:AssertionError: Invalid device id的问题
2021-05-15 16:13:42
最强大最好最全的javascript 验证表单的例子
2010-03-14 11:26:00
python中class(object)的含义是什么以及用法
2023-08-07 22:00:19
php 查找数组元素提高效率的方法详解
2023-11-15 02:51:08
Python基于DFA算法实现内容敏感词过滤
2023-07-25 20:14:11
![](https://img.aspxhome.com/file/2023/2/90562_0s.png)
Django如何实现内容缓存示例详解
2022-02-23 15:33:01
![](https://img.aspxhome.com/file/2023/8/82518_0s.png)