[英]Function not returning a boolean, returns None always
The following code returns None
instead of True
, when the input shows that it should clearly return True
, what is the error here? 以下代码返回
None
而不是True
,当输入表明它应该明确返回True
,这是什么错误?
def checkminus(j):
linp = []
for a in j:
if a == '-':
if len(linp) > 0:
linp = []
return False
quit()
else:
linp.append(a)
else:
linp.append(a)
checklen(linp)
def checklen(k):
l = len(k)
print(l)
if l>0:
return True
else:
return False
print(checkminus(['-','5','5','8','2']))
You forgot to return the checklen()
return value when you call it: 您在调用它时忘记返回
checklen()
返回值:
checklen(linp)
Add a return
there: 在此处添加
return
:
return checklen(linp)
Note that >
already gives you either True
or False
, so you can just return that directly: 请注意,
>
已经给您True
或False
,因此您可以直接将其返回:
def checklen(k):
l = len(k)
return l > 0
Another way of would be to use bool(l)
; 另一种方法是使用
bool(l)
; lists are False
when empty, True
otherwise. 列表为空时为
False
,否则为True
。
Simplifying checkminus()
: 简化
checkminus()
:
def checkminus(j):
linp = []
for a in j:
if a == '-':
if linp:
return False
linp.append(a)
return bool(linp)
which sounds to me as if you wanted to make sure -
is only at the start of the list, or not present at all. 在我看来,您似乎想确保
-
仅在列表的开头,或者根本不存在。
If so, this is easier: 如果是这样,这会更容易:
def checkminus(j):
return len(j) > 0 and '-' not in j[1:]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.