Python 的逻辑运算符 AND

标签 python operator-keyword

我对使用 Python 中的逻辑运算符得到的结果有点困惑。我是初学者,使用几本书进行学习,但它们并没有像我想要的那样详细解释。

这是我自己的代码:

five = 5
two = 2

print five and two

>> 2

好像只是输出了两个变量。

five = 5
two = 2
zero = 0

print five and two and zero

所以,我添加了另一个变量整数。然后我打印并得到以下输出:

>> 0

Python 在后台发生了什么?为什么输出不是 7 或 5、2。

最佳答案

Python bool 运算符返回最后评估的值,而不是 True/False。 docs对此有一个很好的解释:

The expression x and y first evaluates x; if x is false, its value is returned; otherwise, y is evaluated and the resulting value is returned.

关于Python 的逻辑运算符 AND,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18195322/

相关文章:

python - 尝试在一行 if 语句中使用 pass 关键字时出错

python - 将 groupby 结果的值与新列 Python Pandas 中的数据框合并

python - Django:N个应用程序共享1个数据库

c++ - 运算符重载 - 内联非成员函数

c++ - C++ 中的迭代器

python - 谷歌应用引擎 Python Cron

python - 在字典中找到一个值然后得到键

java - 使用 Java 驱动程序在 MongoDB 中进行高级逻辑运算

Python/Django -- "and"运算符和 "&"运算符之间有什么区别

c# - 在 C# 中重载 = 运算符