计算 Python 中列表中正数的总和

Compute the sum of the positive numbers in a list in Python

为考试而学习...这可能是一个问题,但我被卡住了,无法弄清楚我做错了什么。

def theSum(aList):
    s = 0 
    for x in aList:
        if x > 0:
            s+=x
    return theSum

你的逻辑似乎是正确的,但你的代码中有几个缩进和变量错误。

而不是 returning 函数本身,你应该 return s:

def theSum(aList):
    s = 0 
    for x in aList:
       if x > 0:
           s = s + x
    return s

>>> print theSum([-1, 1, -2, 2])
3