布尔语句在应为false时返回true(使用and&or)

时间:2019-10-01 03:03:12

标签: python python-3.x boolean

我有一个使用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。

2 个答案:

答案 0 :(得分:1)

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时使用布尔值,或者如果要检查是否将布尔值与not一起使用这是False

答案 1 :(得分:0)

您要通过使用括号or来强制条件仅对所需的数据进行()的计算。

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

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