CodingBat > Warmup-1 > parrot_trouble

这是我作为程序员的第一个问题,我正在自学 Python,希望您能帮助我弄清楚为什么我对这个问题的回答是错误的。

我知道解决方案更简单,语法上可能更正确,但我想知道为什么我的代码根本不起作用。

我正在处理的问题:

链接: https: //codingbat.com/prob/p166884

粘贴在这里的问题:我们有一只大声说话的鹦鹉。“小时”参数是当前小时时间,范围为 0..23。如果鹦鹉正在说话并且时间是 7 点之前或 20 点之后,我们就有麻烦了。如果我们有麻烦,则返回 True。

parrot_trouble(True, 6) → True parrot_trouble(True, 7) → False parrot_trouble(False, 6) → False

我的答案:

def parrot_trouble(talking, hour):

        if talking == True and hour < 7 == True or hour > 20 == True:

            return(True)

结果:


Expected    Run     

parrot_trouble(True, 6) → True  None    X   

parrot_trouble(True, 7) → False None    X   

parrot_trouble(False, 6) → False    None    X   

parrot_trouble(True, 21) → True None    X   

parrot_trouble(False, 21) → False   None    X   

parrot_trouble(False, 20) → False   None    X   

parrot_trouble(True, 23) → True None    X   

parrot_trouble(False, 23) → False   None    X   

parrot_trouble(True, 20) → False    None    X   

parrot_trouble(False, 12) → False   None    X   

解决方案:


def parrot_trouble(talking, hour):

  return (talking and (hour < 7 or hour > 20))

      Need extra parenthesis around the or clause

      since and binds more tightly than or.

      and is like arithmetic *, or is like arithmetic +

我在小时布尔表达式周围尝试了括号,但这也不起作用:


def parrot_trouble(talking, hour):

        if talking == True and (hour < 7 == True or hour > 20 == True):

            return(True)

我不确定我的想法哪里出了问题。我感谢您的帮助。


跃然一笑
浏览 100回答 2
2回答

慕雪6442864

这里的问题是您使用此语句的语法(hour&nbsp;<&nbsp;7&nbsp;==&nbsp;True&nbsp;or&nbsp;hour&nbsp;>&nbsp;20&nbsp;==&nbsp;True)当你已经声明 hour < 7 时,你不需要放置 '== true'。只需将其更改为(hour&nbsp;<&nbsp;7&nbsp;or&nbsp;hour&nbsp;>&nbsp;20)

杨__羊羊

def parrot_trouble(talking, hour):&nbsp; &nbsp; &nbsp; &nbsp; if talking == True and (hour<7 or hour>20):&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return True&nbsp; &nbsp; &nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return False
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python