【问题标题】:Logic code in python giving the wrong answerpython中的逻辑代码给出了错误的答案
【发布时间】:2018-07-25 13:21:13
【问题描述】:

给定一周中的某一天,编码为 0=Sun,1=Mon,2=Tue,...6=Sat,以及一个指示我们是否在度假的布尔值,返回一个格式为“7:00”的字符串" 指示闹钟何时响起。工作日的闹钟应该是“7:00”,周末应该是“10:00”。除非我们在度假,否则工作日应该是“10:00”,周末应该是“休息”。

我的代码:

  def alarm_clock(day,vacation):
  if(vacation):
      if(day == 0 | day == 6):
          return "off"
      return "10:00"
  else:
      if(day == 0 | day == 6):
          return "10:00"
      return "7:00"

有输入:

print(alarm_clock(0,True))

我的代码在应该“关闭”时返回“10:00”

有输入:

print(alarm_clock(0,False))

我的代码返回“7:00”,应该是“10:00”

我的代码中的错误在哪里?

【问题讨论】:

  • if(day == 0 or day == 6): ?在 python 中使用or

标签: python-3.x logic


【解决方案1】:

改成这样:

def alarm_clock(day,vacation):
    if(vacation):
        if(day == 0 or day == 6):
            return "off"
        return "10:00"
    else:
        if(day == 0 or day == 6):
            return "10:00"
        return "7:00"

print(alarm_clock(0,True))

结果:

off

管道没有按照您的预期执行:Pipe character in Python 实际上是位运算符。 :)

【讨论】:

    【解决方案2】:

    正如您在official documentation 中看到的,Python 中的logical "or" operatoror,而不是|,后者是bitwise operator

    【讨论】:

      【解决方案3】:

      您使用的是按位或“|”。您需要使用逻辑或“或”

      def alarm_clock(day,vacation):
        if(vacation):
            if(day == 0 or day == 6):
                return "off"
            return "10:00"
        else:
            if(day == 0 or day == 6):
                return "10:00"
            return "7:00"
      

      【讨论】:

        猜你喜欢
        • 2021-07-21
        • 2018-11-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多