【问题标题】:Python interpreter evaluates expression 4 < 5 to True. Why then does 4 < 5 == True return False?Python 解释器将表达式 4 < 5 评估为 True。那么为什么 4 < 5 == True 返回 False?
【发布时间】:2019-07-01 16:20:09
【问题描述】:

在解释器中弄乱了值和概念并遇到了一个逻辑绊脚石,因为 4

【问题讨论】:

    标签: python-3.x comparison operators


    【解决方案1】:
    >>> 4<5
    True
    >>> 4<5 == True
    False
    >>> (4<5) == True
    True
    >>>
    

    我希望这能消除您的疑虑。 4&lt;5 == True 评估为 4&lt;5 and 5 == True 总体返回 False,因为 4&lt;5 为 True,但 5 == True 为 False。这是因为&lt;== 具有相同的优先级。

    【讨论】:

    • 谢谢杰。那么这是格式或优先顺序问题还是其他问题?不是从鼹鼠山上造山,而是 True and True == True 是 True ,True and False == False 也是 True 。
    • 这是运算符的优先级和关联性问题。避免这种情况的最佳方法是显式添加括号。
    【解决方案2】:

    来自 Python documentation

    形式上,如果 a, b, c, ..., y, z 是表达式,并且 op1, op2, ..., opN 是 比较运算符,则 a op1 b op2 c ... y opN z 等价于 a op1 b 和 b op2 c 和 ... y opN z,除了每个表达式是 最多评估一次。

    根据本规范,4 &lt; 5 == True 等于 4 &lt; 5 and 5 == True(在 Python 中,operator precedence 等于 (4 &lt; 5) and (5 == True)),其中 4 &lt; 5True,但 5 == TrueFalse。所以True and FalseFalse

    【讨论】:

      【解决方案3】:

      在 Python3 中:4 &lt; 5 == True 等价于 4 &lt; 5 and 5 == True,其计算结果为 False,因为 5 != True

      注意&lt;== 具有相同的优先级。

      文档供参考https://docs.python.org/3/reference/expressions.html#comparisons

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-03-15
        • 1970-01-01
        • 2015-03-22
        • 2014-02-16
        • 2020-01-26
        • 1970-01-01
        • 2011-05-04
        • 1970-01-01
        相关资源
        最近更新 更多