Fra*_*ank 0 python string for-loop if-statement
我试过寻找答案,但似乎没有任何帮助.我弄完了:
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
Run Code Online (Sandbox Code Playgroud)
无论字符串如何,它总是返回True.
你几乎把它弄好了,但问题是,一旦你看到一个非元音的角色,你就会立即返回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.
Run Code Online (Sandbox Code Playgroud)
重要的是要记住,return阻止函数的其余部分运行,因此只有在确定函数已完成计算时才返回.在你的情况下,return False即使我们没有检查整个字符串,我们也可以安全地看到一个元音.