逻辑"和"运算符如何在Python中使用整数?

Smi*_*son 5 python

所以,我正在玩翻译,并输入以下内容:

In [95]: 1 and 2
Out[95]: 2

In [96]: 1 and 5
Out[96]: 5

In [97]: 234324 and 2
Out[97]: 2

In [98]: 234324 and 22343243242
Out[98]: 22343243242L

In [99]: 1 or 2 and 9
Out[99]: 1
Run Code Online (Sandbox Code Playgroud)

最初我认为它与False和True值有关,因为:

In [101]: True + True
Out[101]: 2

In [102]: True * 5
Out[102]: 5
Run Code Online (Sandbox Code Playgroud)

但这似乎并不相关,因为False总是为0,而且从上面的试验来看,它似乎不是输出的最大值.

我不能在这里诚实地看到这种模式,并且在文档中找不到任何东西(老实说,我真的不知道如何有效地寻找它).

那么,怎么做

int(x) [logical operation] int(y)
Run Code Online (Sandbox Code Playgroud)

在Python工作?

Dan*_*owe 13

从Python文档:

表达式x and y首先评估x; 如果x为false,则返回其值; 否则,y将评估并返回结果值.

这正是您的实验所发生的事情.您的所有x值都为true,因此y返回值.

https://docs.python.org/3/reference/expressions.html#and


Jea*_*tan 6

它适用于Python中的每个项目,它不依赖于整数.

not x   Returns True if x is True, False otherwise
x and y Returns x if x is False, y otherwise
x or y  Returns y if x is False, x otherwise
Run Code Online (Sandbox Code Playgroud)

1为True,因此它将返回2