简体   繁体   English

为什么 10 和 5 在 python 中返回 5 和 5 和 10 返回 10? 基本上它在和操作符之后返回第二个 int 值,而不考虑值

[英]Why 10 and 5 returns 5 and 5 and 10 returns 10 in python? Basically it returns the second int after and operator irrespective of value

I was looking into python "and" operator and found out:我正在研究python“and”运算符并发现:

>>> 10 and 5
5
>>> 5 and 10
10

Think of statement logic and which operand determines the value of the entire expression:想想语句逻辑以及哪个操作数决定了整个表达式的值:

and : and

  • the first falsy operand makes the expression False regardless of what comes after无论后面是什么,第一个假操作数都会使表达式为False
  • if there are only truthy operands, the last one settles it如果只有真实操作数,最后一个解决它

Examples:例子:

>>> 5 and 0
0
>>> 0 and 5
0 
>>> 5 and 0 and 3
0 
>>> 10 and 5
5
>>> 5 and 10
10

or : or

  • the first truthy operand makes the expression True regardless of what comes after无论后面是什么,第一个真实操作数都会使表达式为True
  • if there are only falsy operands, the last one settles it如果只有假操作数,最后一个解决它

Examples:例子:

>>> 5 or 0
5
>>> 0 or 5
5 
>>> 5 or 0 or 3
5 
>>> 10 or 5
10
>>> 5 or 10
5

Shot-Circuit behaviour:短路行为:

Note that the rest of the expression is not even evaluated, which is relevant if you chain egfunction calls or other expressions with side effects:请注意,表达式的其余部分甚至不会被计算,如果您将 egfunction 调用或其他具有副作用的表达式链接起来,这很重要:

>>> 4/0 or 5
ZeroDivisionError
>>> 5 or 4/0
5
>>> func1() or func2() and func3()
# func2 and func3 might never be called

Right-Left-Associativity左右结合性

This is kind of directly required for the short-circuit behaviour, but not completely intuitive, especially compared to Python's arithmetic operators:这是短路行为的直接要求,但并不完全直观,尤其是与 Python 的算术运算符相比:

a or b and c or d == (a or (b and (c or d)))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Python:Readline在10行后返回错误 - Python: Readline returns error after 10 lines 函数为以10为底的int()返回无效的文字:'' - Function returns invalid literal for int() with base 10: '' 启动Python进程后,wait()返回-1,errno = 10 - wait() returns -1, errno=10 after launching Python process 将带有 Python Pandas 的 HTML 文件读入 dataframe 返回基数为 10 的 int() 的无效文字 - Reading HTML file with Python Pandas into dataframe returns invalid literal for int() with base 10 Scrapy 在表中的第 10 行之后返回“无” - Scrapy Returns 'None' after the 10th row in table 为什么 1 / [(x ^ 2 - 1) ^ 0.5 - 1] 在 x > 10^9 时返回 ZeroDivisionError? - Why 1 / [(x ^ 2 - 1) ^ 0.5 - 1] returns a ZeroDivisionError when x > 10^9? Python 接受一个名字和 10 个分数并返回名字和 6 个最高分数的程序 - Python program that takes in a Name and 10 Scores and Returns the Name and 6 highest Scores Python Popen.waitpid返回“ [Errno 10]没有子进程” - Python Popen.waitpid returns “[Errno 10] No child processes” Django ElasticSearch 仅返回 10 个行集 - Django ElasticSearch returns only 10 rowsets 质量中心计算返回此错误ValueError:int()的无效文字的基数为10:'' - Centre of mass calculation returns this error ValueError: invalid literal for int() with base 10: ''
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM