0

We just learned for loops in class for about five minutes and we were already given a lab. I am trying but still not getting what I need to get. What I am trying to do is take a list of integers, and then only take the odd integers and add them up and then return them so if the list of integers was [3,2,4,7,2,4,1,3,2] the returned value would be 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])

the error code reads

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
  • 1
    Iterate over ls, not f(ls). Commented Apr 5, 2013 at 15:34
  • Missing parens...: print(f([2,5,4,6,7,8,2])) Commented Apr 5, 2013 at 15:35

2 Answers 2

5

Just a couple of minor mistakes:

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
Sign up to request clarification or add additional context in comments.

Comments

1

You're missing the parenthesis in the function call

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

rather than

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.