Python邏輯操作的三大重要環(huán)節(jié)
Python邏輯操作的過程中有三個重要的環(huán)節(jié)。每一個都需要我們十分注意,下面我們就看看如何才能更好的運用Python邏輯操作中三個環(huán)節(jié)來完善我們的應(yīng)用。希望大家在今后的學(xué)習(xí)中有所收獲。舉例:
- #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
嚴格的說,邏輯操作符的操作數(shù)應(yīng)該為布爾表達式。但Python對此處理的比較靈活。即使操作數(shù)是數(shù)字,解釋器也把他們當成“表達式”。非0的數(shù)字的布爾值為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中,空字符串為假,非空字符串為真。非零的數(shù)為真。
數(shù)字和字符串之間、字符串之間的邏輯操作規(guī)律是:
對于and操作符:只要左邊的表達式為真,整個表達式返回的值是右邊表達式的值,否則,返回左邊表達式的值。對于or操作符:只要兩邊的表達式為真,整個表達式的結(jié)果是左邊表達式的值。如果是一真一假,返回真值表達式的值,如果兩個都是假,比如空值和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 = 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
以上就是對Python邏輯操作的相關(guān)介紹。希望大家有所收獲。
【編輯推薦】