我想在用戶輸入列表中添加所有的負整數,但函數始終返回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.你在第一次迭代中返回'sum'。 3.'input'函數將返回一個字符串,而不是數字列表。您需要拆分字符串並將字符串轉換爲數字。 – thefourtheye