Python 3 print([1, 2] and 3) 输出 3

Python 3 print([1, 2] and 3) outputs 3

我输入了

print([1,2] and 3)

结果是

3

这是怎么发生的?为什么结果是3?

我猜 [1,2] 被认为是 True。但是我不知道后端进程是如何工作的。

This Article From Quora 说得最好:

Python uses and and or operators in a slightly different way.

It doesn’t return pure boolean values (i.e. True or False) as someone working with a language like Java might expect.

It returns one of the operand based on conditions, and the truth value of that operand determines the boolean value if used in a conditional statement.

and: Return the first Falsy value if there are any, else return the last value in the expression.

or: Return the first Truthy value if there are any, else return the last value in the expression.

and 是布尔运算符。

它 return 是计算结果为 False 的第一个操作数或最后一个计算结果为 True 的操作数。 在这种情况下,它将 return 3。如果列表为空,它将 return 为空列表,如您在本例中所见:

>>> [] and 3
[]

布尔运算——与、或、非

这些是布尔运算,按优先级升序排列:

Operation Result Notes
x or y if x is false, then y, else x (1)
x and y if x is false, then x, else y (2)
not x if x is false, then True, else False (3)

备注:

  1. 这是一个短路运算符,因此如果第一个参数为假,它只计算第二个参数。

  2. 这是一个短路运算符,因此它仅在第一个参数为真时才计算第二个参数。

  3. not 的优先级低于非布尔运算符,因此 not a == b 被解释为 not (a == b),而 a == not b 是语法错误。

Please check this official python doc for more information

当布尔“与”运算符为“真”时,它return表达式中last/left最“真”的值。

>>> print(3 and 5)
5
>>> print((3 and [1,4] and [1,2] ))
[1, 2]

布尔运算符为 0 给出“False”,当“and”运算符结果为“False”时,它return表达式中的第一个“False”值。

>>> print([1,2] and 0)
0

>>> z = False 
>>> print((3 and z and 0 ))
False