Preface
In the course of learning Python today, I found that Python did not switch this syntax. So I wanted to do it in Python. Body
In this article, we simulate the use of the switch to the normal database additions and deletions to the operation of the corresponding, such as ' Select
Corresponds to ' Select action ' and so on. 1. Simple If-else
As we know, there are if statements in Python, and when you learn C, the alternative that comes out when you learn if-else is switch, which can be a perfect substitute for each other, and you need to be aware that else if it is simplified to elif in Python. As shown below:
#!/usr/bin/env python user_cmd = raw_input ("please input your choice:\n") if usercmd = = "selec
t"
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. Using the dictionary here we use the dictionary function: Dict.get (key, Default=none). key--the value to find in the dictionary, default--returns the default value if the value of the specified key does not exist. As follows: <pre> ' #!/usr/bin/env python usercmd = raw_input ("please input your choice:\n") dic = {' Sele CT ': ' Select Action ', ' Update ': ' Update action ', ' delete ': ' Delete action ', ' Insert ': ' Insert action '} Defaultitem = ' Invalid choice! ' Ops = Dic.get (usercmd,defaultitem) print Ops ' </pre> # 3. The general form of combining a lambda function with a dictionary lambda is the keyword lambda followed by the One or more arguments, followed by a colon, and then an expression. Lambda isAn expression instead of a statement. It can appear where the Python syntax does not allow DEF to appear, and this is no longer described here. As follows: <pre> ' #!/usr/bin/env python usrcmd = raw_input ("please input your choice:\n") dic = {' Selec T ': Lambda: "select action", ' Update ': lambda: "update action", ' delete ': Lamb
DA: "delete action", ' Insert ': lambda: "insert action"
Print Cho[usr_cmd] ()Conclusion
Six months before the rough study of Python, and then has not how to use, now to review, feel a lot of knowledge to forget, to continue reviewing ...