几年之前写的这篇博客,最近看了一下python3.6.5的tutorial,有新的理解补充如下,若有不对,敬请指正,谢谢!
1. and or not 有优先级,not 优先级最高,or 优先级最低
These have lower priorities than comparison operators; between them, not
has the highest priority and or
the lowest, so that A and not B or C
is equivalent to (A and (not B)) or C
2. and 与 or 有短路现象;(下面红色部分谷歌翻译)当用作普通值而不是布尔值时,短路运算符的返回值是最后一次评估的参数。
The Boolean operators and
and or
are so-called short-circuit operators: their arguments are evaluated from left to right, and evaluation stops as soon as the outcome is determined.For example, if A
and C
are true but B
is false, A and B and C
does not evaluate the expression C
. When used as a general value and not as a Boolean, the return value of a short-circuit operator is the last evaluated argument.
———————————————————————————————————-
原文:
>>> 1 and 2 and 3
3
>>> False and 1 and 2
False
>>> 1 and 2 and 3 and 4
4
>>> 1 and 2 and 3 and False
False
>>> 1 or 2 or 3
1
>>> False or 1 or 2
1
>>> 1 and 2 and 3 or False and 1
3
在python中and与or执行布尔逻辑运算,但返回的是实际值。
1.全为and,如果都为真,则返回最后一个变量值;如果为假,则返回第一个假值
2.全为or,如果都为假则返回最后一个值;如果为真,则返回第一个真值
3.and 与or:
>>> 1 and 2 or False
2
>>> False and 1 or 2
2
(a and b ) or c :如果a and b为真则结果为b,若a and b为假,结果为c,其实原理与and和or的一样,类似于C中到bool?a:b
另外:or有短路现象,如果为真,后面的不执行(PS:谢谢提醒)
>>>False and 1 or 2
2
>>> 1 or 2 and False
1
>>> (1 or 2 ) and False
False