Python中实现switch功能实例解析
作者:最爱彩虹糖 时间:2021-06-03 05:35:09
前言
今天在学习python的过程中,发现python没有switch这个语法。于是就想在python中如何才能实现这个功能呢?
正文
本文中我们对switch的使用模拟为正常的数据库的增删改查操作的对应,如'select
对应'select action'等。
1.简单的if-else
正如我们所知,python中有if语句,而且当时学习C的时候,学到if-else时引出的的替代品就是switch,两者可以完美的互相替代,需要注意的是在python中else if简化成了elif。如下所示:
#!/usr/bin/env python
user_cmd = raw_input("please input your choice:\n")
if usercmd == "select"
ops = "select action"
elif usercmd == "update"
ops = "update action"
elif usercmd == "delete"
ops = "delete action"
elif usercmd == "insert"
ops = "insert action"
else
ops = "invalid choice!"
print ops
`</pre>
2.使用字典
这里我们使用到了字典的函数:dict.get(key, default=None)。key--字典中要查找的值,default--如果指定键的值不存在时,返回该默认值。如下所示:
#!/usr/bin/env python
usercmd = raw_input("please input your choice:\n")
dic = {'select':'select action','update':'update action','delete':'delete action','insert':'insert action'}
defaultitem = 'invalid choice!'
ops = dic.get(usercmd,defaultitem)
print ops
3.使用lambda函数结合字典
lambda的一般形式是关键字lambda后面跟一个或多个参数,紧跟一个冒号,以后是一个表达式。lambda是一个表达式而不是一个语句。它能够出现在Python语法不允许def出现的地方,这里就不再多加描述。如下所示:
#!/usr/bin/env python
usrcmd = raw_input("please input your choice:\n")
dic = {'select': lambda : "select action",
'update': lambda : "update action",
'delete': lambda : "delete action",
'insert': lambda : "insert action"}
print cho[usr_cmd]()
来源:http://blog.csdn.net/LS7011846/article/details/52626626
标签:python,switch,字典
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Python命令行参数定义及需要注意的地方
2022-09-16 02:34:39
![](https://img.aspxhome.com/file/2023/9/115689_0s.png)
Python字典取键、值对的方法步骤
2021-12-12 15:26:12
![](https://img.aspxhome.com/file/2023/0/128750_0s.png)
Python自动安装第三方库的小技巧(pip使用详解)
2021-07-15 19:32:48
![](https://img.aspxhome.com/file/2023/0/131730_0s.jpg)
python用opencv批量截取图像指定区域的方法
2021-10-14 09:07:33
JavaScript Memoization
2008-05-01 12:48:00
详解django使用include无法跳转的解决方法
2023-04-08 06:13:54
手把手教你Python yLab的绘制折线图的画法
2023-03-11 21:21:43
![](https://img.aspxhome.com/file/2023/7/112587_0s.png)
python在地图上画比例的实例详解
2023-06-22 20:54:00
![](https://img.aspxhome.com/file/2023/1/99011_0s.png)
浅谈python 导入模块和解决文件句柄找不到问题
2023-12-07 03:40:07
ASP给长的标题加省略号...
2008-02-22 14:39:00
Python matplotlib模块及柱状图用法解析
2023-11-24 01:04:33
![](https://img.aspxhome.com/file/2023/5/117335_0s.png)
Python语音合成的项目实战(PyQt5+pyttsx3)
2021-06-15 09:14:13
![](https://img.aspxhome.com/file/2023/9/128549_0s.jpg)
浅谈JavaScript的自动垃圾收集机制
2023-08-13 15:18:57
Python将多个excel表格合并为一个表格
2021-10-18 22:50:22
![](https://img.aspxhome.com/file/2023/8/81818_0s.jpg)
Thinkphp3.2.3反序列化漏洞实例分析
2023-06-14 11:27:37
![](https://img.aspxhome.com/file/2023/4/55514_0s.jpg)
用Python编写一个简单的FUSE文件系统的教程
2021-11-21 01:30:36
echarts实现晶体球面投影的实例教程
2023-09-02 10:35:12
![](https://img.aspxhome.com/file/2023/4/56124_0s.png)
JS实现二维数组横纵列转置的方法
2023-08-29 21:54:05
![](https://img.aspxhome.com/file/2023/6/56206_0s.jpg)
Python3 json模块之编码解码方法讲解
2021-07-15 17:29:15
Python实现获取系统临时目录及临时文件的方法示例
2022-03-11 00:42:04