1. 程式人生 > >Python邏輯運算

Python邏輯運算

一.運算子種類

1.比較運算子 > ,< ,   >=  ,<=  , != , ==  
2.賦值運算子 =, +=,-=,*=,/=,**=,%=
3.成員運算子 in not in 
4.算數運算子 + ,-,*,/,**,%
5.邏輯運算子 not and or 

 二.運算子運算順序

括號>算數運算子(+,-,*,/,%,//,**)>比較操作符(>,<,!=,=)>not>and>or

 三.and,or,not邏輯運算結果

1.在and關係中,兩者都為真,選擇後者

print(1 and 2)                 
print(2 and 1)                   
print(True and 1)            
print(1 and True)
運算結果:
2
1
1
True

2.在and關係中,有一個為假,那麼結果就是假

print(1 and 0)                
print(0 and 1)                
print(1 and False)            
print(False and 1)      
運算結果:
0
0
False
False     


3.在and關係中,多個假,那麼結果是出現的第一個假,因為發現假,那麼後面的結果不會影響最終結果,所以邏輯運算結束

print(0 and False)            
print(False and 0)  
運算結果: 0 False


4.在or關係中,多個假,沒有真,那麼一定是最後一個假作為結果,因為當發現第一個假,並不代表後面沒有真,所以繼續邏輯運算直到最後

print(False or 0)            
print(0 or False) 
運算結果:
0
False

          
5.在or關係中,有一個真,那麼結果就是出現的第一個真,那麼發現真,後面的結果不會影響最終結果,所以邏輯運算結束

print(1 or 2)                
print(2 or 1)                
print(0 or 1)                
print(1 or 0)

運算結果:

1
2
1
1