5.2. Boolean Operations — and, or, not
These are the Boolean operations, ordered by ascending priority:
Operation | Result | Notes |
---|---|---|
x | if | (1) |
x | if | (2) |
not | if | (3) |
Notes:
- This is a short-circuit operator, so it only evaluates the second argument if the first one is
False. - This is a short-circuit operator, so it only evaluates the second argument if the first one is
True. - not
has a lower priority than non-Boolean operators, so not a == b is interpreted as not (a == b), and a == not b is a syntax error.
1.x and y :
Ex:
Ex:
>>> 1 and 2
2
>>> 1 and 0
0
>>> 0 and 1
0
【释】依次找False值,找到就输出第一个False值,若到结尾还没False值,就输出最后一个True值。
2.x or y :
Ex:
Ex:
>>> 1 or 2
1
>>> 0 or 1
1
>>> 0 or 0
0
>>> 0 or 1 or 3
1
>>> {} or 0 or []
[]
【释】依次找True值,找到就输出第一个True值,若到结尾还没有True值,就输出最后一个False值。
3. not
>>> not -1
False
>>> not 0
True
>>> not 1
False
>>> not 2
False
>>> not []
True
>>> not ('')
True
【释】这就是所谓的负负得正(负指的是False,所有为空、零,("")为True值,元组中有一个空元素,元组不为空,所以为真值)
当然啦,and or not ...都可以拼接的的比如 x and y and (a or b and c) ,判断顺序是从左往右,优先执行括号中的噢!本例中的a or b and c = Result会优先判断,然后再判断 x and y and Result
原创所有,转载请附明本文链接,谢谢!