2013-04-05 114 views
0

我們剛剛在課上學習了循環約五分鐘,我們已經給了一個實驗室。我正在嘗試,但仍然沒有得到我需要得到的東西。我想要做的是取一個整數列表,然後只取奇數整數並加起來然後返回它們,所以如果整數列表是[3,2,4,7,2,4,1, 3,2]返回的值是14for循環的問題

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 
+1

遍歷'ls',不'F(LS)'。 – 2013-04-05 15:34:49

+0

丟失的零食......:print(f([2,5,4,6,7,8,2]))' – FatalError 2013-04-05 15:35:50

回答

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

你錯過了在括號函數調用

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

而非

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