【发布时间】:2020-01-30 07:39:54
【问题描述】:
我有一个布尔语句使用and 和or 来确定它是真还是假。结果应该是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