def has_a_vowel(a_str):
for letter in a_str:
if letter in "aeiou":
return True
else:
return False
print("Done!")
调用此函数将仅检查第一个元素...如何在返回True或False之前使其在字符串中运行? 谢谢
答案 0 :(得分:4)
最简单的方法是在循环外删除else: return False
和return False
:
def has_a_vowel(a_str):
for letter in a_str:
if letter in "aeiou":
return True # this leaves the function
print("Done!") # this prints only if no aeiou is in the string
return False # this leaves the function only after the full string was checked
或更简单:
def has_a_vowel(a_str):
return any(x in "aeiou" for x in a_str)
(尽管不会打印完成)。
阅读: