2015-05-05 19 views
1

我只是做了我想解決這個問題的一個非常簡化的版本:使用不檢查,如果真

test = [False] 
for element in test: 
    if value not False: 
    return True 

這是檢查的元素是在列表True。但是,這返回在線3上的SyntaxError

+2

'if test:'will work。 '如果沒有測試:'當查找'falsy'值時。 –

+0

我想你的意思就像'如果元素' – Ronald

+0

@羅納德你是對的我搞砸了。 – Sundrah

回答

2

這是因爲

value not False 

不是一個有效的Python語法。你可能想

value is not False 

的另一個問題是,你想element而不是value

-4

它看起來像你想迭代布爾值列表,並返回True,只要你找到一個真正的?如果是這樣你需要測試的元素,而不是名單:

test = [False] 
for element in test: 
    if element not False: 
     return True 
+0

這修復了'NameError',但**不** **'SyntaxError'。 – jonrsharpe

1

存在語法錯誤,因爲if value not False沒有意義。要檢查if value is not False

test = [False] 
for element in test: 
    if element is not False: 
     return True 
0

Python有內置any功能,檢查一個序列的每個元素True -ness,直到它找到一個:在linked documentation長相

>>> any([False, False, False, True, False] 
True 

代碼非常喜歡你的:

def any(iterable): 
    for element in iterable: 
     if element: 
      return True 
    return False