Python implements switch function instance analysis

  • 2020-07-21 08:36:25
  • OfStack

preface

In the process of learning python today, I found that python does not have the grammar of switch. So how do you do that in python?

The body of the

In this paper, our use of switch is simulated as the corresponding operation of adding, deleting, modifying and checking the normal database, such as 'select
'select action' and so on.

1. Simple ES18en-ES19en

As we know, there are if statements in python, and when learning C, the substitution induced by learning ES25en-ES26en is switch. The two can be perfectly substituted for each other. It should be noted that in python, else if is simplified to elif. As shown below:


#!/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. Use a dictionary

Here we use the dictionary function dict.get (key, default=None). key-- The value to look for in the dictionary, default-- returns the default value if the specified key does not exist. As shown below:


#!/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

3. Use the lambda function to combine the dictionary

The generic form of lambda is the keyword lambda followed by one or more parameters, followed by a colon, followed by an expression. lambda is an expression, not a statement. It can appear in places where the Python syntax does not allow def, which is not described here. As shown below:


#!/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]()

conclusion

That is the end of this article on Python to implement switch functional instance parsing, I hope to help you. Interested friends can continue to refer to other related topics in this site, if there is any deficiency, welcome to comment out. Thank you for your support!


Related articles: