【问题标题】:bool and int types in boolean contexts布尔上下文中的 bool 和 int 类型
【发布时间】:2015-07-12 07:02:51
【问题描述】:

我在一个布尔上下文中有这段代码:

True and False or 2  

输出:2

对该表达式的类型检查导致int

接下来,我将代码修改为:

True and False or True 

输出:True 这个表达式的类型检查导致bool

  • 为什么第一个代码中的输出是2
  • 表达式不应该计算为布尔值吗?
    如果不是,为什么?

【问题讨论】:

    标签: python boolean logical-operators


    【解决方案1】:

    这里你只需要知道OR operand的定义。基于python文档:

    表达式 x 或 y 首先计算 x;如果 x 为真,则返回其值;否则,评估 y 并返回结果值。

    因此,由于orprecedence 低于and,因此您的表达式计算如下:

    (True and False) or 2
    

    等于以下:

    False or 2
    

    因此,根据前面的文档,结果将是正确对象的值,即 2。

    【讨论】:

    • 你的意思是short circuit evaluation
    • 我明白了。我的问题是关于输出而不是评估方法。为什么输出是2 而不是True
    • @KshitijSaraogi 这是逻辑,但正如文档中提到的 python 而不是 True 返回值。
    【解决方案2】:

    在 Python 中,当使用“and”和“or”时,表达式使用所涉及的对象进行计算,而不是像在许多其他语言中那样使用布尔值。

    所以:

    1 and 2 will evaluate to 2
    1 or 2 will evaluate to 1 (short-circuit)
    1 and "hello" will evaluate to "hello"
    

    ...等等

    如果你想要布尔值,只需将整个表达式用 bool(..) 括起来

    进一步阅读: http://www.diveintopython.net/power_of_introspection/and_or.html https://docs.python.org/2/reference/expressions.html#boolean-operations

    【讨论】:

      【解决方案3】:

      当您说True and False 时,它的评估结果为False。 然后你有False or 2,它将评估为2 现在True and False or True 将评估为True,但表达式中的最后一个True。这是由于operator precedence

      >>> True and False
      False
      >>> False or 2
      2
      >>> 
      

      输出是2 而不是True,因为True and False or 2 就像

      var = (True and False)
      if var:
          print(var)
      else:
          print(2)
      

      产生

      2
      

      因为True and False 将始终评估为False

      【讨论】:

      • 我得到了评估的方法。我的问题是为什么输出是2 而不是True
      • 真的是这样吗?老实说,我觉得这很奇怪
      • 你能分享任何链接以进一步阅读这个学派
      【解决方案4】:

      我认为您很清楚 andor.之间的运算符优先级根据 Python 文档,返回 object

      >>> 1 and 2
      

      将根据快捷键评估返回2。 等等。

      【讨论】:

        猜你喜欢
        • 2014-09-07
        • 2012-11-28
        • 1970-01-01
        • 2010-09-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-07-23
        相关资源
        最近更新 更多