for循环中的缩进错误

Indentation error in for loop

问题是:

Finish the function sum_of_over_fives that loops over number_list and adds to the total only the numbers greater than 5. Then it should return the total.

def sum_of_over_fives(number_list):
       total = 0
       for number in number_list:
           number >5
             total += number
       return total

我收到 "number >5" 行的缩进错误,但我直觉认为该行是错误的。

您可以使用 built-ins filtersum:

total = sum(filter(lambda x: x > 5, number_list))

正如@Mitch 和@StephenRauch 所指出的,您的逻辑没有问题,唯一的问题是您的缩进和 number > 5 应该是 if statement

根据 PEP 8 文档,您必须确保 indentation of your function body is 4 目前为 8。

那么唯一剩下的就是将 if:number > 5 放在一起。这是您的最终代码,其中包含更正的缩进和正确的 if 语句:

def sum_of_over_fives(number_list):
    total = 0
    for number in number_list:
        if number > 5:
            total += number
    return total

print(sum_of_over_fives([1,2,3,4,5,6,7]))
>>> 
13

但是就像@a_guest 所说的那样,有更好的方法来完成您想要做的事情。

希望对您有所帮助:)。