【问题标题】:Using return statements in Python loops [duplicate]在 Python 循环中使用 return 语句[重复]
【发布时间】:2019-02-25 16:11:47
【问题描述】:
def has_a_vowel(a_str):
    for letter in a_str:
        if letter in "aeiou":
            return True
        else:
            return False
    print("Done!")

调用这个函数只会检查第一个元素...我怎样才能让它在返回 True 或 False 之前遍历字符串? 谢谢你

【问题讨论】:

    标签: python loops


    【解决方案1】:

    在循环外删除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)
    

    (虽然不会打印 Done)。

    阅读:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-05-21
      • 2017-11-17
      • 1970-01-01
      • 1970-01-01
      • 2011-08-17
      • 2014-08-28
      相关资源
      最近更新 更多