Python中實現switch功能__Python

來源:互聯網
上載者:User
前言

今天在學習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(&quot;please input your choice:\n&quot;)if usercmd == &quot;select&quot;    ops = &quot;select action&quot; elif usercmd == &quot;update&quot;    ops = &quot;update action&quot; elif usercmd == &quot;delete&quot;    ops = &quot;delete action&quot; elif usercmd == &quot;insert&quot;    ops = &quot;insert action&quot; else     ops = &quot;invalid choice!&quot;print ops`</pre>## 2.使用字典這裡我們使用到了字典的函數:dict.get(key, default=None)。key--字典中要尋找的值,default--如果指定鍵的值不存在時,返回該預設值。如下所示:<pre>`#!/usr/bin/env pythonusercmd = 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 pythonusrcmd = 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,然後一直沒怎麼用,現在來溫習,感覺好多知識點都忘了,繼續複習中。。。



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.