在Python循环中使用return语句

时间:2019-02-25 16:11:48

标签: python loops

def has_a_vowel(a_str):
    for letter in a_str:
        if letter in "aeiou":
            return True
        else:
            return False
    print("Done!")

调用此函数将仅检查第一个元素...如何在返回True或False之前使其在字符串中运行? 谢谢

1 个答案:

答案 0 :(得分:4)

最简单的方法是在循环外删除else: return Falsereturn 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)

(尽管不会打印完成)。

阅读: