【问题标题】:Why us Python code is evaluating to false when it is true?为什么我们的 Python 代码在为真时评估为假?
【发布时间】:2015-10-20 18:19:07
【问题描述】:

所以我使用了下面的代码,它一直评估为 False,但它是 True。作为一个 Python 2.7 菜鸟,我不知道为什么。

s = 'Z_15'

if s.startswith('Z_') & int(s[2:]) >= 15:
    new_format = True
else:
    new_format = False

print new_format

还有这个变化:

s = 'Z_15'
sYr = int(s[2:])

if s.startswith('Z_') & sYr >= 15:
    new_format = True
else:
    new_format = False

print new_format

我已经评估了连词的两个部分,它们评估为 True,所以不确定我做错了什么。

【问题讨论】:

  • 您是否有意使用位运算符& 而不是逻辑运算符and
  • new_format = s.startswith('Z_') and sYr >= 15可能更清楚

标签: python python-2.7 logic


【解决方案1】:

& 是位运算符,它比普通逻辑运算符具有higher precedence。因此,您的表达式被解析为:

if (s.startswith('Z_') & int(s[2:])) >= 15:

哪个(在这种情况下)是:

if (True & 15) >= 15:

简化为:

if 1 >= 15:

这是一个明显错误的条件。


要解决此问题,请使用 and 运算符,该运算符执行逻辑 and 并具有正确的优先级。

【讨论】:

    【解决方案2】:

    当你使用逻辑和运算符时,你会得到正确的答案,而不是按位和运算符

    将您的代码修改为:

    s = 'Z_15'
    
    if s.startswith('Z_') and int(s[2:]) >= 15:
        new_format = True
    else:
        new_format = False
    
    print new_format
    

    你可以read this article for more information

    【讨论】:

    • 这对我有用。事实上,s.startswith('Z_') and int(s[2:]) 的计算结果为 15。但是使用& 失败了,因为我们得到s.startswith("Z_") & int(s[2:]) 评估为1
    • @travelingbones 精确
    【解决方案3】:

    除了其他答案,您可以这样做

    s = 'Z_15'
    new_format = s.startswith('Z_') and int(s[2:]) >= 15
    print new_format
    

    【讨论】:

      猜你喜欢
      • 2018-07-01
      • 2016-08-25
      • 1970-01-01
      • 2019-06-04
      • 2011-10-11
      • 1970-01-01
      • 2014-05-19
      • 2022-10-20
      • 1970-01-01
      相关资源
      最近更新 更多