Python邏輯操作中的三大應用方案
Python邏輯在運作中有不少的問題需要解決。下面我們就詳細的看看如何進行實際的操作。在實際的使用中有三種:and、or、not。分別對應與、或、非。希望大家有所收獲。
舉例:
- #coding:utf-8
- test1 = 12
- test2 = 0
- print (test1 > test2) and (test1 > 14) #result = False
- print (test1 < test2) or (test1 > -1) #result = True
- print (not test1) #result = False
- print (not test2) #result = True
嚴格的說,邏輯操作符的操作數應該為布爾表達式。但Python邏輯操作對此處理的比較靈活。即使操作數是數字,解釋器也把他們當成“表達式”。非0的數字的布爾值為1,0的布爾值為0.
舉例:
- #coding:utf-8
- test1 = 12
- test2 = 0
- print (test1 and test2) #result = 0
- print (test1 or test2) #result = 12
- print (not test1) #result = Flase
- print (not test2) #reslut = True
在Python邏輯操作中,空字符串為假,非空字符串為真。非零的數為真。
數字和字符串之間、字符串之間的邏輯操作規律是:
對于and操作符:只要左邊的表達式為真,整個表達式返回的值是右邊表達式的值,否則,返回左邊表達式的值對于or操作符:只要兩邊的表達式為真,整個表達式的結果是左邊表達式的值。
如果是一真一假,返回真值表達式的值,如果兩個都是假,比如空值和0,返回的是右邊的值。(空值或0)舉例:
- #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 = 1212 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
以上就是對Python邏輯的相關的介紹。
【編輯推薦】