Python中實現switch功能執行個體解析,pythonswitch

來源:互聯網
上載者:User

Python中實現switch功能執行個體解析,pythonswitch

前言

今天在學習python的過程中,發現python沒有switch這個文法。於是就想在python中如何才能實現這個功能呢?

本文

本文中我們對switch的使用類比為正常的資料庫的增刪改查操作的對應,如'select
對應'select action'等。

1.簡單的if-else

正如我們所知,python中有if語句,而且當時學習C的時候,學到if-else時引出的的替代品就是switch,兩者可以完美的互相替代,需要注意的是在python中else if簡化成了elif。如下所示:

#!/usr/bin/env pythonuser_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 pythonusercmd = 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 pythonusrcmd = 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]()

總結

以上就是本文關於Python中實現switch功能執行個體解析的全部內容,希望對大家有所協助。感興趣的朋友可以繼續參閱本站其他相關專題,如有不足之處,歡迎留言指出。感謝朋友們對本站的支援!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.