一个lin中的返回函数

2024-06-16 09:32:45 发布

您现在位置:Python中文网/ 问答频道 /正文

Fill in the box with python code that will make the program behavior match the comments. You may not make any other changes to the code or add code outside the parenthesis " ( )" .

def bypass_line(age, has_acces_card):
''' (int, bool) -> bool
Return True if and only if the person's age is greater than 50 or
they have a access card as indicated by has_access_card.
'''


return (                    )

这是我正在做的练习题。我进退两难,我知道怎么写代码。。。你知道吗

即:

def bypass_line(age, has_vip):
    if age >70 or has_vip =="yes":
        return True
    return False

但是如何在()中编写一行代码以便回答问题呢?你知道吗


Tags: orthetrueagemakereturnifaccess
2条回答

在您的旁路线函数,您可以简单地写

return age > 50 or has_acces_card == "yes"
因为我更喜欢C++,所以我喜欢组织这样的代码。它帮助我想得更清楚。你知道吗

return (age > 50) or (has_acces_card == "yes")

不管是哪种方式,代码只是检查

  • 年龄大于50岁
  • 有门禁卡

如果其中一个为真(因此or),函数将返回True。否则,它将返回一个false。你知道吗

逻辑与if语句中的逻辑完全相同,只是结果TrueFalse被用在return语句中(仍然有相同的表达式,只是结果被用在其他地方)。您可以在任何地方使用该表达式(或任何表达式),例如在print中,变量的定义,作为函数的参数。。。逻辑总是一样的。你知道吗

像这样:

def bypass_line(age, has_acces_card):
    return age > 50 or has_acces_card == "yes"

这基本上是返回由if语句计算的表达式本身。因为表达式已经在if语句中返回TrueFalse,所以它在这里也会这样做。你知道吗

您的if表达式已生成一个布尔值;它是TrueFalse。您可以直接退回:

return age > 70 or has_vip == "yes"

这基本上就是if测试的内容;获取表达式,将其传递给bool(),然后查看它是True还是False。这里不需要bool(),因为比较运算符(>==)本身已经返回TrueFalse

>>> age = 60
>>> age > 70
False
>>> age = 80
>>> age > 70
True

相关问题 更多 >