上市功能困难

编写一个名为“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

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


FFIVE
浏览 169回答 3
3回答

慕田峪9158850

你的 return 语句缩进太深;你应该在 for 循环之后返回它。也不sum是一个好名字,因为它是您覆盖的内置函数。并且您应该添加1到总和(您正在计算)而不是x它本身。您也可以使用内置函数尝试此操作sum:def&nbsp;counting(number): &nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;sum(29.88&nbsp;<&nbsp;x&nbsp;<&nbsp;48.05&nbsp;for&nbsp;x&nbsp;in&nbsp;number)(这实际上是sum(1 for x in number if 29.88 < x < 48.05)并且有效的缩写,因为Trueis basic1并且Falseis basic&nbsp;0)。

慕运维8079593

或者与您的相似:def counting(number):&nbsp; &nbsp; c = 0&nbsp; &nbsp; for x in number:&nbsp; &nbsp; &nbsp; &nbsp; if 29.88 < x < 48.05:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; c += 1&nbsp; &nbsp; return c或者可以做单线,len:def counting(number):&nbsp; &nbsp; return len([29.88 < x < 48.05 for x in number])
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python