首页 > 解决方案 > 列表功能困难

问题描述

编写一个名为“counting”的函数,该函数将数字列表作为参数,并返回输入中 29.88 到 48.05 之间不包括这些端点的值的数量。(下面是我的代码)

def counting(number):
    sum = 0
    for x in number:
        if (29.88 < x < 48.05):
            sum = sum + x
        return sum

如何返回输入中的值的数量而不是输入的第一个数字?

标签: python

解决方案


your return statement is indented too deep; you should return it after the for loop. also sum is not a good name as it is a built-in function that you overwrite.

and you should add 1 to the sum (you are counting) and not x itself.

you could also try this using the built-in function sum:

def counting(number):
    return sum(29.88 < x < 48.05 for x in number)

(this is actually short for sum(1 for x in number if 29.88 < x < 48.05) and works because True is basically 1 and False is basically 0).


推荐阅读