-2

I am trying to add all of the negative integers in a user input list, but the function always returns 0 as the answer. It works if I include the list as part of the function, but not when its user input. The code I have is:

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))
thefourtheye
  • 233,700
  • 52
  • 457
  • 497
user5514218
  • 11
  • 1
  • 1
  • 1
  • 2
    Three major problems. 1. You are reassigning an empty list. So, there are no elements to add. 2. You are returning `sum` in the first iteration itself. 3. `input` function will return a string, not a list of numbers. You need to split the string and convert the strings to numbers yourself. – thefourtheye Nov 02 '15 at 02:53

4 Answers4

5
sum(i for i in alist if i < 0)

Done. It's Python, it has to be simple!

Dima Tisnek
  • 11,241
  • 4
  • 68
  • 120
1

remove the second line of your code, it sets the input to an empty list no matter what your input is.

0

You assign an empty list to userList every time you enter the function, how can it not be 0?

Further more, the function input() seems not able to handle a list of inputs.

So I think you can do this:

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))
sunhs
  • 391
  • 1
  • 6
0

You could always just do if and elif statements to determine whether or not to add a number to a list and then take the sum of the list. My prompt is making a list of 100 number with random integers from -100 to 100. Then finding the sum of all the negative numbers.

    import random
    def SumNegative():
         my_list = []
         for i in range(100):
             x = random.randint(-100, 100)
             if x > 0:
                 pass
             elif x < 0:
                 my_list.append(x)
          print(sum(my_list))
    SumNegative()
Nick
  • 1