邏輯運算的優先級
在沒有括號的情況下:not > and > or 同一優先級按照從左至右的順序計算。
int轉換為bool,bool只有真假兩個值,所以數字0轉換為bool就等於false,非零數字轉換為bool就等於True。
OR
print(1 or 2)#結果為1 print(2 or 1)#結果為2 print(0 or 2)#結果為2 print(0 or 100)#結果為100 結論:前面為真,返回前面的;前面為假,則返回后面的
print(1 > 2 or 2 > 1)#1>2為假,所以返回后面的:True(2>1=True) print(2 > 1 or 1 > 2)#2>1為真,所以返回前面的結果:True
結論:數字會返回數字,而邏輯運算只有True,False。
AND
print(1 and 2)#結果為2 print(2 and 1)#結果為1 print(0 and 2)#結果為0 print(0 and 100)#結果為0 結論:and 和 or 相反。 前面為真,返回后面;前面為假,則返回前面的 print(1 > 2 and 2 > 1)#1>2為假,所以返回前面的結果:False print(2 > 1 and 1 >2)#2>1為真,所以返回后面的結果:False