2015-01-02 320 views

回答

7

操作如果没有元素是False(或同等的值,如0)返回最后元件。

例如,

>>> 1 and 4 
4 # Given that 4 is the last element 
>>> False and 4 
False # Given that there is a False element 
>>> 1 and 2 and 3 
3 # 3 is the last element and there are no False elements 
>>> 0 and 4 
False # Given that 0 is interpreted as a False element 

操作返回第一元件不是False。如果没有这样的值,则返回False

例如,

>>> 1 or 2 
1 # Given that 1 is the first element that is not False 
>>> 0 or 2 
2 # Given that 2 is the first element not False/0 
>>> 0 or False or None or 10 
10 # 0 and None are also treated as False 
>>> 0 or False 
False # When all elements are False or equivalent 
1

这会引起混乱 - 你不是第一个被它绊倒。

Python将0(零),False,None或空值(如[]或'')视为false,其他都视为true。

的 “与” 和 “或” 运算符返回根据这些规则操作数之一:

  • “x和y” 是指:如果x为假,则x,否则ÿ
  • “×或Y”是指:如果x是 假,则Y,否则x

您引用不一样清楚,因为它可以解释这个页面,但他们的榜样是正确的。

1

我不知道这是否有帮助,但是扩展@ JCOC611的答案,我认为它是返回确定逻辑语句值的第一个元素。因此,对于一串'和',第一个False值或最后一个True值(如果所有值均为True)确定最终结果。同样,对于一串'或',第一个True值或最后一个False值(如果所有值都是False)确定最终结果。

>>> 1 or 4 and 2 
1 #First element of main or that is True 
>>> (1 or 4) and 2 
2 #Last element of main and that is True 
>>> 1 or 0 and 2 
1 
>>> (0 or 0) and 2 
0 
>>> (0 or 7) and False 
False #Since (0 or 7) is True, the final False determines the value of this statement 
>>> (False or 7) and 0 
0 #Since (False or 7) is True, the final 0(i.e. False) determines the value of this statement) 

第一行读为1或(4和2),因为1使最终语句为真,所以它的值被返回。第二行由'and'语句管理,所以最后的2是返回的值。在接下来的两行中使用0作为False也可以显示这一点。

最终,我通常比较喜欢在布尔语句中使用布尔值。取决于与布尔值相关的非布尔值总是让我感到不安。另外,如果你用布尔值构造一个布尔型staement,这个返回确定整个语句值的值的想法更有意义(对我来说,无论如何)