[英]I am trying to understand class and function and can't seem to figure out what is wrong with my code
[英]I can't figure out what is wrong with this function?
这是它应该返回的
如果所有项目都是真实的,则返回 True。
Examples:
>>> all_true([1, True, 'oregonstate'])
True
>>> all_true([0, 1, 2])
False
"""
这是我写的
def all_true(items):
for i in items:
if i == True:
return True
else:
return False
pass
不知道为什么它不起作用,有人可以帮忙吗?
您的 function 只返回列表中第一项的真实性,因为它总是在第一次迭代时返回。
你想做这样的事情:
def all_true(items):
for i in items:
if not i:
return False
return True
注意这个all_true
function已经存在于Python中,是内置的all
function。
两个问题。 首先,您返回的是第一个True
事物。 事实上,不管怎样,您首先返回的不是True
就是False
。 由于您同时返回了if
和它的else
子句,因此循环将始终在第一次迭代时返回。 更微妙一点,但如果列表中没有任何值,它将返回None
。
其次,如果您想要“真实”,请不要专门与True
进行比较。 foo == True
是False
。 相反,让if
做 boolean 测试
def all_true(items):
for i in items:
if not i:
return False
return True
all
和any
是做同样事情的内置函数。 通常最好使用它们。
“所有项目都是真实的”在逻辑上等同于“没有项目是虚假的”。
def all_true(items):
for i in items:
if not i:
return False
return True
因为 0 是假的。 此外,无需为此实现您自己的 function,而是使用 Python 的内置all()
function!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.