Python邏輯操作符__Python

來源:互聯網
上載者:User

剛開始看python,覺得這個邏輯操作符和其他語言有些區別,所以就記錄下來。
Python的邏輯操作有三種:and、or、not。分別對應與、或、非。

嚴格的說,邏輯操作符的運算元應該為布林運算式。但Python對此處理的比較靈活。
即使運算元是數字,解譯器也把他們當成“運算式”。
非0的數位布爾值為1,0的布爾值為0.
在Python中,Null 字元串為假,非Null 字元串為真。非零的數為真。

對於and操作符a and b:
只要左邊的運算式為真,整個運算式返回的值是右邊運算式的值,否則,返回左邊運算式的值
對於or操作符 a or b:
只要左邊的運算式為真,整個運算式返回的值是左邊運算式的值,否則,返回右邊運算式的值
對於not操作符 not a:
如果 a 為 True,返回 False 。如果 a 為 False,它返回 True。
舉例:
假設變數 a 為 10, b為 20
(a and b) 返回 20。
(a or b) 返回 10。
not(a and b) 返回 False

 #coding:utf-8 test1 = 12 test2 = 0 test3 = '' test4 = "First" print test1 and test3   #result = '' print test3 and test1   #result = '' print test1 and test4   #result = "First" print test4 and test1   #result = 12 print test1 or test2    #result = 12 print test1 or test3    #result = 12 print test3 or test4    #result = "First" print test2 or test4    #result = "First" print test1 or test4    #result = 12 print test4 or test1    #result = "First" print test2 or test3    #result = '' print test3 or test2    #result = 0

聯繫我們

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