我做错什么了?我对Python不熟悉

2024-05-28 20:38:59 发布

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

Complete the body of the function sign (with signature below) in agreement with the details specified above.

def sign(t):
    "Returns +1 for t>=0, -1 otherwise"

解决方案:

def sign(t):

sign = lambda t: -1 if t < 0 else 1 if t >=0

以上显示语法错误。我做错什么了?它显示的名字“sign”没有定义


Tags: oftheinifdefwithagreementfunction
2条回答

似乎你只需要一个小函数。这就是你要找的吗

def sign(t):
    if t < 0:
        return -1
    else:
        return 1

还有一件事是你的lambda有问题。如果你把它当作一个普通函数来展开,它会是这样的:

def sign(t):
    if t < 0:
        return -1
    else:
       return 1 if t >= 0

所以,只有两种情况。t要么小于0,要么大于或等于0。因此,以下代码将起作用:

sign = lambda t: -1 if t < 0 else 1
print(sign(2)) # will return 1

就其本身而言

def sign(t):
    "Returns +1 for t>=0, -1 otherwise"

是语法上完整的函数定义。它不做任何事情(除了returnNone),但是docstring足以使body变为非空,就像您将它定义为

def sign(t):
    pass

相反

您需要做的是在函数中添加一个实际的主体,以便它按照docstring描述的方式运行

def sign(t):
    "Returns +1 for t>=0, -1 otherwise"
    if t >= 0:
        return 1
    else:
        return -1

或者

def sign(t):
    "Returns +1 for t>=0, -1 otherwise"
    return 1 if t >= 0 else -1    

相关问题 更多 >

    热门问题