【问题标题】:Why is my Python code not evaluating booleans correctly?为什么我的 Python 代码没有正确评估布尔值?
【发布时间】:2021-03-22 23:19:01
【问题描述】:

我是 Python 的初学者,我在 YouTube 上看到了 Cory Schafer 编写的关于布尔值和条件的教程。当他试图展示 Python 认为哪些值是 False 时,他有一个片段。他对它们一一进行了测试,但我想知道是否有更有效/更有趣的方法来做到这一点,所以我尝试提出这个 for 循环语句。我期望输出是 8 行 Evaluated to False,但我不断得到 Evaluated to True。有人可以启发我吗?谢谢!

condition = (False, None, 0, 0.00, '', (), [], {})

for i in condition:
    if condition:    # It is assumed that condition == true here, right? 
        print('Evaluated to True')
    else:
        print('Evaluated to False ')

#OUT: 
Evaluated to True
Evaluated to True
Evaluated to True
Evaluated to True
Evaluated to True
Evaluated to True
Evaluated to True
Evaluated to True

【问题讨论】:

    标签: python python-3.x for-loop boolean boolean-logic


    【解决方案1】:

    if condition 更改为if i。您想测试已从 condition 元组中提取的每一项,而不是测试整个元组 8 次。

    更清晰的命名可以避免这个问题。我建议总是给集合的复数名称加上 s 最后。然后就可以这样写了,读起来更自然:

    conditions = (False, None, 0, 0.00, '', (), [], {})
    
    for condition in conditions:
        if condition:    # It is assumed that condition == true here, right? 
            print('Evaluated to True')
        else:
            print('Evaluated to False ')
    

    【讨论】:

    • 谢谢!我认为更清晰的命名位实际上非常聪明。将从现在开始这样做!
    【解决方案2】:

    小心!您正在评估整个元组,每次在您的循环中(因此,评估同一个对象)而不是单个项目。此外,您得到了 True,因为非空列表/元组/字典将始终评估为 True,与您在最后 3 次迭代中看到的评估为 False 的空列表相比。

    当您评估为 i 而不是 condition 时,您应该更改该行:

    condition = (False, None, 0, 0.00, '', (), [], {})
    
    for i in condition:
        if i: 
            print('Evaluated to True')
        else:
            print('Evaluated to False')
    

    这理所当然地返回:

    Evaluated to False 
    Evaluated to False 
    Evaluated to False 
    Evaluated to False 
    Evaluated to False 
    Evaluated to False 
    Evaluated to False 
    Evaluated to False 
    

    【讨论】:

    • 谢谢你!我也想知道为什么我一直得到 True,只是澄清你的解释为什么,是因为我的“条件”元组不是空的,即使它充满了所谓的空和/或假的元素?
    • 没错,如果您评估元组,您正在评估该对象,而不是其中的内容。
    【解决方案3】:

    在 if 语句中用 i 替换条件

    condition = (False, None, 0, 0.00, '', (), [], {})
    
    for i in condition:
        if condition:
            print("Evaluated to True")
        else:
            print("Evaluated to False")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-04
      • 2022-11-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多