2015-11-02 113 views
-3

我想在用戶輸入列表中添加所有的負整數,但函數始終返回0作爲答案。如果我將該列表作爲函數的一部分包含在內,但它在用戶輸入時不起作用。我有的代碼是:列表中的負整數的總和

def sumNegativeInts(userList): 
    userList = [] 
    sum = 0 
     for i in userList: 
      if i < 0: 
      sum = sum + i 
      return sum 

userList = input("Enter a list of +/- integers: ") 
print(sumNegativeInts(userList)) 
+2

三大問題。你正在重新分配一個空白列表。所以,沒有要添加的元素。 2.你在第一次迭代中返回'sum'。 3.'input'函數將返回一個字符串,而不是數字列表。您需要拆分字符串並將字符串轉換爲數字。 – thefourtheye

回答

0

您每次輸入函數時都會爲userList指定一個空列表,它怎麼能不是0?

此外,函數input()似乎無法處理輸入列表。

所以我認爲你可以這樣做:

def sumNegativeInts(userList): 
    sum = 0 
    for i in userList: 
     if i < 0: 
      sum += i 
    return sum 

inputData = raw_input('some prompts') 
userList = [int(i) for i in inputData.split(' ')] 
print(sumNegativeInts(userList)) 
2
sum(i for i in alist if i < 0) 

完成。它是Python,它必須簡單!

1

刪除代碼的第二行,它會將輸入設置爲空列表,而不管輸入是什麼。