Python內置類型(2)——布爾運算


 

python中bool運算符按優先級順序分別有orandnot, 其中orand為短路運算符

not先對表達式進行真值測試后再取反

not運算符值只有1個表達式,not先對表達式進行真值測試后再取反,返回的結果不是True就是False

>>> expression1 = ''
>>> expression2 = '1'
>>> not expression1
True
>>> not expression2
False

orand運算符返回的結果是操作符兩邊的表達式中的符合邏輯條件的其中一個表達式的結果

在其它語言中,比如C#,bool運算的結果肯定也是bool值;但是python中不是這樣的,它返回的是滿足bool運算條件的其中一個表達式的值。

  • x or y

xTrue,則結果為x;若xFalse, 則結果為y

>>> expression1 = '1'
>>> expression2 = '2'
>>> expression1 or expression2
'1'
>>> expression2 or expression1
'2'
  • x and y

xFalse,則結果為x;若xTrue, 則結果為y

>>> expression1 = ''
>>> expression2 = {}
>>> expression1 and expression2
''
>>> expression2 and expression1
{}

orand運算符是短路運算符

短路運算符的意思是,運算符左右的表達式的只有在需要求值的時候才進行求值。比如說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

orand運算符可以多個組合使用,使用的時候將以此從左到右進行短路求值,最后輸入結果

表達式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運算符的優先級比orand高,一起使用的時候,會先計算not,再計算orand的值

>>> 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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM