Python學習筆記之條件運算式

來源:互聯網
上載者:User

今天寫代碼的時候,發現python不支援C風格的 con? exp1:exp2 這樣的條件運算式,後來一查,發現原來在2.5裡面新增了該功能,不過是以另外一種方式來表達的,下面是在python 2.7.1文檔中提供的說明,這裡做了簡單的翻譯:

 

版本2.5中新添功能

conditional_expression ::=  or_test ["if" or_test "else" expression]

expression ::= conditional_expression | lambda_form

條件運算式(有時候又叫做“三元操作符”),它在python所有的操作符中優先順序最低

運算式x if C else y,首先計算條件C(不是x),如果C為True,x被計算,返回x計算的值,否則y被計算,返回y計算的值

 

更多關於條件運算式的細節,可以參考PEP(Python Enhanced Proposals)308

 

其中or_test在文檔中的描述是這樣子的,這其實就是布爾運算運算式

or_test ::= and_test | or_test "or" and_test

and_test ::= not_test | and_test "and" not_test

not_test ::= comparison | "not" not_test

 

例如,想要想將x,y中較大者複製給z,可以這樣做

z=x if x>y else y

聯繫我們

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