[英]What am I doing wrong here? I am new to 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"
solution:解决方案:
def sign(t):
sign = lambda t: -1 if t < 0 else 1 if t >=0
Above shows syntax error.以上显示语法错误。 What am I doing wrong here?
我在这里做错了什么? it kind of shows name 'sign' not defined
它有点显示名称“符号”未定义
Seems like all you need a is small function.似乎您只需要一个小功能。 Is this what you're looking for?
这是你要找的吗?
def sign(t):
if t < 0:
return -1
else:
return 1
Also, one thing is wrong with your lambda.另外,你的 lambda 有一个问题。 If you expand it as if it was a normal function it would look like this:
如果将其扩展为普通函数,它将如下所示:
def sign(t):
if t < 0:
return -1
else:
return 1 if t >= 0
So, there are only two cases.所以,只有两种情况。 Either t is less than 0, or it is greater than or equal to zero.
t 要么小于 0,要么大于或等于 0。 So, the following code will work:
因此,以下代码将起作用:
sign = lambda t: -1 if t < 0 else 1
print(sign(2)) # will return 1
By itself,通过它自己,
def sign(t):
"Returns +1 for t>=0, -1 otherwise"
is a syntactically complete function definition.是一个语法完整的函数定义。 It doesn't do anything, (except return
None
) but the docstring is sufficient to make the body non-empty, as if you had defined it as它什么都不做,(除了 return
None
)但文档字符串足以使主体非空,就好像您已将其定义为
def sign(t):
pass
instead.反而。
What you need to do is add an actual body to the function so that it behaves the way the docstring describes.您需要做的是向函数添加一个实际的主体,以便它按照文档字符串描述的方式运行。
def sign(t):
"Returns +1 for t>=0, -1 otherwise"
if t >= 0:
return 1
else:
return -1
or或者
def sign(t):
"Returns +1 for t>=0, -1 otherwise"
return 1 if t >= 0 else -1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.