2015-10-14 65 views
0

我試過尋找答案,但似乎沒有任何幫助。我已經完成:如果String中沒有字符是Python中的元音,則返回True

def noVowel(s): 
    'return True if string s contains no vowel, False otherwise' 
    for char in s: 
     if char.lower() not in 'aeiou': 
      return True 
     else: 
      return False 

無論字符串,它總是返回True。

+4

好吧,我敢打賭,如果你在字符串中傳入'a',它會返回'False',因爲你總是在第一個字符後面返回(並且從不檢查其他字符)。 – nneonneo

回答

2

隨着any和短路特性:

def noVowel(s): 
    return not any(vowel in s.lower() for vowel in "aeiou") 
5

你幾乎得到它的權利,但問題是,一旦你看到一個字符是一個非元音,你返回True然後向右那裏。你想返回True你確信所有是非元音後:

def noVowel(s): 
    'return True if string s contains no vowel, False otherwise' 
    for char in s: 
     if char.lower() in 'aeiou': 
      return False 
    return True # We didn't return False yet, so it must be all non-vowel. 

重要的是要記住,return停止運行函數的休息,所以只有當你確定迴歸很重要該功能已完成計算。在你的情況下,即使我們沒有檢查整個字符串,只要我們看到元音,就可以安全return False

+0

我簡直就是在發帖後試過這個哈哈。非常感謝你! – Frank

相關問題