python中bool運算符按優先級順序分別有
or
、and
、not
, 其中or
、and
為短路運算符
not
先對表達式進行真值測試后再取反
not
運算符值只有1個表達式,not
先對表達式進行真值測試后再取反,返回的結果不是True
就是False
>>> expression1 = ''
>>> expression2 = '1'
>>> not expression1
True
>>> not expression2
False
or
、and
運算符返回的結果是操作符兩邊的表達式中的符合邏輯條件的其中一個表達式的結果
在其它語言中,比如C#,bool運算的結果肯定也是bool值;但是python中不是這樣的,它返回的是滿足bool運算條件的其中一個表達式的值。
x or y
:
若 x
為True
,則結果為x
;若x
為False
, 則結果為y
。
>>> expression1 = '1'
>>> expression2 = '2'
>>> expression1 or expression2
'1'
>>> expression2 or expression1
'2'
x and y
:
若 x
為False
,則結果為x
;若x
為True
, 則結果為y
。
>>> expression1 = ''
>>> expression2 = {}
>>> expression1 and expression2
''
>>> expression2 and expression1
{}
or
、and
運算符是短路運算符
短路運算符的意思是,運算符左右的表達式的只有在需要求值的時候才進行求值。比如說x or y
,python從左到右進行求值,先對表達式x
的進行真值測試,如果表達式x
是真值,根據or
運算符的特性,不管y
表達式的bool結果是什么,運算符的結果都是表達式x
,所以表達式y
不會進行求值。這種行為被稱之為短路特性。
#函數功能判斷一個數字是否是偶數
def is_even(num):
print('input num is :',num)
return num % 2 == 0
#is_even(1)被短路,不會執行
>>> is_even(2) or is_even(1)
input num is : 2
True
>>> is_even(1) or is_even(2)
input num is : 1
input num is : 2
True
or
、and
運算符可以多個組合使用,使用的時候將以此從左到右進行短路求值,最后輸入結果
表達式x or y and z
,會先對x or y
進行求值,然后求值的結果再和z
進行求值,求值過程中依然遵循短路原則。
#is_even(2)、is_even(4)均被短路
>>> is_even(1) and is_even(2) and is_even(4)
this num is : 1
False
# is_even(1)為False,is_even(3)被短路
# is_even(1) and is_even(3)為False,is_even(5)需要求值
# is_even(1) and is_even(3) or is_even(5)為False,is_even(7)被短路
>>> is_even(1) and is_even(3) or is_even(5) and is_even(7)
this num is : 1
this num is : 5
False
not
運算符的優先級比or
、and
高,一起使用的時候,會先計算not
,再計算or
、and
的值
>>> is_even(1) or is_even(3)
this num is : 1
this num is : 3
False
>>> not is_even(1) or is_even(3)
this num is : 1
True
>>> is_even(1) or not is_even(3)
this num is : 1
this num is : 3
True
>>>
not
運算符的優先級比==
、!=
低,not a == b
會被解釋為 not (a == b)
, 但是a == not b
會提示語法錯誤。
>>> not 1 == 1
False
>>> 1 == not 1
SyntaxError: invalid syntax
>>> not 1 != 1
True
>>> 1 != not 1
SyntaxError: invalid syntax