for循环问题

时间:2013-04-05 15:33:50

标签: python for-loop

我们刚刚在课堂上学习了大约五分钟的循环,我们已经有了实验室。我正在努力,但仍然没有得到我需要得到的东西。我想要做的是获取一个整数列表,然后只取奇数整数并将它们加起来然后返回它们,如果整数列表为[3,2,4,7,2,4,1, 3,2]返回值为14

def f(ls):
    ct=0
    for x in (f(ls)):
        if x%2==1:
            ct+=x
    return(ct)


print(f[2,5,4,6,7,8,2])

错误代码为

Traceback (most recent call last):
  File "C:/Users/Ian/Documents/Python/Labs/lab8.py", line 10, in <module>
    print(f[2,5,4,6,7,8,2])
TypeError: 'function' object is not subscriptable

2 个答案:

答案 0 :(得分:5)

只是一些小错误:

def f(ls):
    ct = 0
    for x in ls:
    #       ^     Do not call the method, but just parse through the list  
        if x % 2 == 1:
            ct += x
    return(ct)
    #     ^  ^ parenthesis are not necessary 

print(f([2,5,4,6,7,8,2]))
#      ^               ^    Missing paranthesis

答案 1 :(得分:1)

你错过了函数调用中的括号

print(f([2,5,4,6,7,8,2]))

而不是

print(f[2,5,4,6,7,8,2])