首页 > 解决方案 > 总是在我的代码中返回循环错误,想知道我需要做什么来修复它?

问题描述

假设 List[int] 已经被导入,我想知道这个问题的最后四行代码有什么问题。每当我尝试运行它时,我都会收到一条错误消息,指出“[第 11 行] 此循环只会运行一次迭代”。为缺乏术语或知识而道歉(我是 python 新手)

def divisible_by_7(lst: List[int]) -> bool:
    """Return True if and only if lst contains an element divisible
    by 7. Otherwise, return False.
    
    >>> divisible_by_7([4,8,21,6])
    True
    >>> divisible_by_7([1,2,8,9])
    False
    """
    for num in lst:
        if num % 7 == 0:
            return True
        return False

标签: pythonsyntax-error

解决方案


只需像这样移动“return False”:

for num in lst:
    if num % 7 == 0:
        return True
return False

推荐阅读