【问题标题】:Using a Boolean in an If-Statement in Python在 Python 的 If 语句中使用布尔值
【发布时间】:2013-05-06 10:04:40
【问题描述】:

我有一些带有 if 语句的代码,其中一个条件是布尔值。但是,CodeSkulptor 说“第 36 行:TypeError:BitAnd 不支持的操作数类型:'bool' 和 'number'”。如果可以的话请帮忙。这就是那段代码的样子。 (我只是更改了所有变量名和 if 语句执行的内容)

thing1 = True
thing2 = 3

if thing2 == 3 & thing1:
   print "hi"

【问题讨论】:

  • 使用 and 代替 &。需要注意的是,在要评估的表达式中使用括号。如果你不这样做,你会发现意想不到的结果。
  • @Imagine: == 的优先级高于and,所以什么都不会发生。
  • @Blender 没错,但引用 python 的禅宗:显式优于隐式。我宁愿添加不必要但澄清的括号,也不愿依赖对运算符优先级的不完善了解。
  • @ValekHalfHeart:我很少看到if (foo == 2) and bar,但如果你觉得它们更清楚,个人偏好添加它们。

标签: python if-statement boolean


【解决方案1】:

您想使用逻辑 and(而不是 &,它是 Python 中的按位与运算符):

if thing2 == 3 and thing1:
   print "hi"

因为你用过&,所以弹出了错误,说:

TypeError: unsupported operand type(s) for BitAnd: 'bool' and 'number'
                                           ^^^^^^

【讨论】:

    【解决方案2】:

    & 是按位与运算符。您想改用逻辑 and

    if thing2 == 3 and thing1:
        print "hi"
    

    【讨论】:

      猜你喜欢
      • 2018-04-17
      • 2013-03-01
      • 2016-11-20
      • 2020-07-30
      • 2013-11-22
      • 1970-01-01
      • 2012-02-09
      • 2021-08-03
      相关资源
      最近更新 更多