【问题标题】:If statement with not equal to condition not working as expected如果不等于条件的语句未按预期工作
【发布时间】:2017-10-21 14:59:03
【问题描述】:

我在 python 中有以下代码,我不知道为什么但它没有按预期工作。

变量 isactive 的值等于“True”,它来自 json 字典。但是,当我在 if 语句下面写下时,程序正在打印“Hola”。请看下面的代码:

response = requests.request("GET", url, headers=headers, params=querystring)
variable = response.text
variable = json.loads(variable)

isactive = lista1[listanumber]['IsActive']

print isactive (ourput for this is giving me "True")

        if isactive != "True":
            print "hola"

但是,上面的 if 语句正在打印“Hola”,我不明白为什么,因为 isactive 变量等于“True”。

你知道可能是什么问题吗?

谢谢

【问题讨论】:

  • isactive的字符串长度是多少?是否包含一些空格?
  • print repr(isactive) 打印什么?
  • 嗯,很奇怪..当我尝试获取 isactive 的长度时,出现以下错误:文件“hoy.py”,第 291 行,在 print len(isactive) TypeError : 'bool' 类型的对象没有 len()
  • @MaximTitarenko 它打印“真”

标签: python if-statement


【解决方案1】:

json 中的 true 被转换为 python True。布尔值,而不是字符串。 在你的比较中,你可以简单地输入if not isActive:

【讨论】:

    【解决方案2】:
    isactive == True and isactive != 'True'
    

    测试:

    if isactive != True:
        print 'hola'
    

    【讨论】:

    • Bienvenido, Jose, porfa marca mi respuesta como solución.
    猜你喜欢
    • 1970-01-01
    • 2012-08-16
    • 2020-10-23
    • 2017-01-10
    • 1970-01-01
    • 2016-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多