Python 中的逻辑运算符 [英] Logical operators in Python
问题描述
在阅读 python 中的逻辑运算符时,我遇到了表达式:
5 和 1
输出:1
5 或 1
输出:5
谁能解释一下这是如何工作的?
我知道逻辑运算符的操作数是布尔
即有据可查的:
x 或 y 如果 x 为假,则为 y,否则为 xx 和 y 如果 x 为假,则为 x,否则为 y
两者都短路(例如,如果 x
是 truthy,or
将不会评估 y
).>
文档还说明了什么被认为是falsy (False
, 0
, None
, 空序列/映射, ...) - 其他的都被考虑真实.
几个例子:
7 和 'a' # ->'一种'[] 或无 # ->没有任何{'a': 1} 或 'abc'[5] # ->{'a': 1};没有从abc"[5] 引发的 IndexError假和 'abc'[5] # ->错误的;没有从abc"[5] 引发的 IndexError
注意最后两条语句是如何显示短路行为的:第二条语句(会引发 IndexError
)没有执行.
您关于操作数是布尔值的说法有点没有实际意义.python 确实有布尔值(实际上只有 2 个:True
和 False
;它们是 int 的子类型).但是python中的逻辑运算只是检查操作数是truthy还是falsy.bool
函数是未在操作数上调用.
术语truthy 和falsy 似乎没有在官方python 文档中使用.但是教 Python 的书籍和这里的社区确实使用了这些术语.在 english.stackexchange.com 上有关于条款的讨论,在 维基百科.
While reading the Logical operators in python i came across with expressions :
5 and 1
output : 1
5 or 1
output : 5
Can anyone explain how is this working ?
I know that the operands of the logical operators are Boolean
that is well documented:
x or y if x is false, then y, else x
x and y if x is false, then x, else y
both short-circuit (e.g. or
will not evaluate y
if x
is truthy).
the documentation also states what is considered falsy (False
, 0
, None
, empty sequences/mappings, ...) - everything else is considered truthy.
a few examples:
7 and 'a' # -> 'a'
[] or None # -> None
{'a': 1} or 'abc'[5] # -> {'a': 1}; no IndexError raised from 'abc'[5]
False and 'abc'[5] # -> False; no IndexError raised from 'abc'[5]
note how the last two show the short-circuit behavior: the second statement (that would raise an IndexError
) is not executed.
your statement that the operands are boolean is a bit moot. python does have booleans (actually just 2 of them: True
and False
; they are subtypes of int). but logical operations in python just check if operands are truthy or falsy. the bool
function is not called on the operands.
the terms truthy and falsy seem not to be used in the official python documentation. but books teaching python and the community here do use these terms. there is a discussion about the terms on english.stackexchange.com and also a mention on wikipedia.
这篇关于Python 中的逻辑运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!