[英]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.