Python逻辑运算符
我目前正在学习Python3,但我不懂逻辑运算符。以下是链接:Python逻辑运算符,python,Python,我目前正在学习Python3,但我不懂逻辑运算符。以下是链接: 首先,它似乎应该返回“真”或“假”,而不是其中一个输入数字。第二,我不明白为什么输出(一个输入数字)是这样的。请帮助,谢谢。如果没有元素为False(或等效值,如0),则运算符和返回最后一个元素 比如说, >>> 1 and 4 4 # Given that 4 is the last element >>> False and 4 False # Given that there is a Fa
首先,它似乎应该返回“真”或“假”,而不是其中一个输入数字。第二,我不明白为什么输出(一个输入数字)是这样的。请帮助,谢谢。如果没有元素为
False
(或等效值,如0
),则运算符和返回最后一个元素
比如说,
>>> 1 and 4
4 # Given that 4 is the last element
>>> False and 4
False # Given that there is a False element
>>> 1 and 2 and 3
3 # 3 is the last element and there are no False elements
>>> 0 and 4
False # Given that 0 is interpreted as a False element
运算符或返回第一个非False
的元素。如果没有这样的值,则返回False
比如说,
>>> 1 or 2
1 # Given that 1 is the first element that is not False
>>> 0 or 2
2 # Given that 2 is the first element not False/0
>>> 0 or False or None or 10
10 # 0 and None are also treated as False
>>> 0 or False
False # When all elements are False or equivalent
这可能令人困惑——你不是第一个被它绊倒的人 Python将0(零)、False、None或空值(如[]或“”)视为False,其他值视为true “and”和“or”运算符根据以下规则返回其中一个操作数:
- “x和y”的意思是:如果x为假,则x为假,否则y为假
- “x或y”是指:如果x是 那么y为假,否则x为假
您引用的页面没有尽可能清楚地解释这一点,但它们的示例是正确的。我不知道这是否有帮助,但为了扩展@JCOC611的答案,我认为它返回了确定逻辑语句值的第一个元素。因此,对于“and”字符串,第一个假值或最后一个真值(如果所有值都为真)决定最终结果。类似地,对于“或”字符串,第一个真值或最后一个假值(如果所有值都为假)确定最终结果
>>> 1 or 4 and 2
1 #First element of main or that is True
>>> (1 or 4) and 2
2 #Last element of main and that is True
>>> 1 or 0 and 2
1
>>> (0 or 0) and 2
0
>>> (0 or 7) and False
False #Since (0 or 7) is True, the final False determines the value of this statement
>>> (False or 7) and 0
0 #Since (False or 7) is True, the final 0(i.e. False) determines the value of this statement)
第一行读取为1或(4和2),因此由于1使最终语句为真,因此返回其值。第二行由'and'语句控制,因此最后的2是返回的值。在接下来的两行中使用0作为False也可以显示这一点
最后,我通常更喜欢在布尔语句中使用布尔值。依赖于非布尔值与布尔值的关联总是让我感到不安。另外,如果你想用布尔值构造一个布尔语句,那么返回决定整个语句值的值的想法就更有意义了(无论如何,对我来说)谢谢。这真让人困惑。。。为什么要把事情复杂化,为了简洁而牺牲可读性?这两个例子让我大吃一惊:
(1和不是1)或(1和1)
返回1
,但(1和不是0)或(1和0)
返回True
???