Python中实现switch功能

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/LS7011846/article/details/52626626

前言

今天在学习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--如果指定键的值不存在时,返回该默认值。如下所示:

<pre>`#!/usr/bin/env python
usercmd = raw_input(&quot;please input your choice:\n&quot;)
dic = {'select':'select action','update':'update action','delete':'delete action','insert':'insert action'}
defaultitem = 'invalid choice!'
ops = dic.get(usercmd,defaultitem)
print ops
`</pre>

3.使用lambda函数结合字典

lambda的一般形式是关键字lambda后面跟一个或多个参数,紧跟一个冒号,以后是一个表达式。lambda是一个表达式而不是一个语句。它能够出现在Python语法不允许def出现的地方,这里就不再多加描述。如下所示:

<pre>`#!/usr/bin/env python
usrcmd = raw_input(&quot;please input your choice:\n&quot;)
dic = {'select': lambda : &quot;select action&quot;,
   'update': lambda : &quot;update action&quot;,
   'delete': lambda : &quot;delete action&quot;,
   'insert': lambda : &quot;insert action&quot;}
print cho[usr_cmd]()

结语

大半年前大略的学习了一下python,然后一直没怎么用,现在来温习,感觉好多知识点都忘了,继续复习中。。。



猜你喜欢

转载自blog.csdn.net/LS7011846/article/details/52626626