【问题标题】:Boolean statement returning true when should be false (Using and & or)当应该为假时返回真的布尔语句(使用和&或)
【发布时间】:2020-01-30 07:39:54
【问题描述】:

我有一个布尔语句使用andor 来确定它是真还是假。结果应该是false,但它返回true。为什么是这样?我该怎么做才能使它实际输出真正的答案。

如果我注释掉最后一部分 (or nighttime==False),它将给我正确的答案,但这是我需要包含的内容,将其设为 and 没有意义,因为我想拥有这样,如果大灯熄灭,则只能在白天或夜间不正确时开车。

      got_car=True
      drunk=False
      gas=2 #(gallons) - gas currently in the tank of the car
      distance=100 #miles from home
      mpg=35 #miles per gallon expected to be used driving home
      nighttime=False
      headlights_out=True

      can_drive=battery_charged==True and got_car==True and drunk==False and gas*mpg>=distance==True and headlights_out==False or nighttime==False
      print(can_drive)

      if can_drive==True:
          print("Drive home.")
      else:
          print("Do not drive home.")

它应该打印 False,因为没有足够的汽油可以让它走完整个距离,但它打印的是 true。

【问题讨论】:

  • 请提供 battery_charged 的​​值以便能够回答您的问题。另外,建议您将括号下的逻辑正确分组。例如。 (True and False) or True or (False and True) and True 有不同的含义:True and False or True or False and True and True.

标签: python python-3.x boolean


【解决方案1】:

您希望通过使用括号 () 强制条件仅评估您想要的数据 or

例如,只有当headlights_out 为假或nighttime 为真时,您才希望can_drive 为真:

can_drive = battery_charged==True and got_car==True and drunk==False and gas*mpg>=distance==True and (headlights_out==False or nighttime==False)

【讨论】:

    【解决方案2】:

    can_drive 有点冗长,您应该在条件中使用括号,因为and 的优先级高于or,因此您可以使用以下内容:

    can_drive= battery_charged and got_car and not drunk and gas * mpg >= distance and (not headlights_out or not nighttime)
    

    您还可以改进can_drive声明之后的代码:

    if can_drive:
        print("Drive home.")
    else:
        print("Do not drive home.")
    

    请记住,将布尔值与True 进行比较是多余的,因此当您想检查它是否为True 时只需使用布尔值,如果您想检查它是否为False,请使用not

    【讨论】:

    • 非常感谢!非常感谢您的回答。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-09
    • 2016-12-20
    • 2014-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-01
    相关资源
    最近更新 更多