在Python循环中使用return语句

2024-04-19 00:18:25 发布

您现在位置:Python中文网/ 问答频道 /正文

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

调用此函数只会检查第一个元素。。。如何让它在返回True或False之前遍历字符串? 谢谢


Tags: infalsetrueforreturnifdefelse
1条回答
网友
1楼 · 发布于 2024-04-19 00:18:25

最好将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)

(但不会打印完成)。你知道吗

读数:

相关问题 更多 >