【问题标题】:Bool issues. And, or, and or, or not布尔问题。和,或,和或,或不
【发布时间】:2019-06-13 23:30:57
【问题描述】:

我正在尝试使用 bool 运行代码,但在使代码正常工作时遇到问题。基本上我必须使用代码来决定在满足某些标准后驾驶是否安全。电池必须是充电器(真),我必须有车(真),我不能喝醉(假),我必须有足够的汽油才能到达我要去的地方,如果是晚上我必须工作头灯。到目前为止,我已经设法一直到加油站,但我似乎无法弄清楚在夜间或白天驾驶工作和非工作头部时的和,或,而不是,或不是语句灯。

battery_charged=True
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=False

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

if can_drive:
    print("Drive home")

else:
    print("Don't drive home.")

【问题讨论】:

  • 提示:如果是白天,你会在意车头灯吗?

标签: python boolean


【解决方案1】:

你的问题在最后一个子句中:

and (nighttime and not headlights_out)

这表示您只能在夜间开着大灯开车。您需要说的是如果是夜间,大灯必须打开。最容易编码的逻辑等价物是“必须是白天,否则我的车头灯必须打开”:

and (not nighttime or not headlights_out):

这应该会让你上路......

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-07
    相关资源
    最近更新 更多