Python - Identify a negative number in a list

Michael picture Michael · Apr 14, 2013 · Viewed 89.2k times · Source

I need help doing a program which should recieve ten numbers and return me the number of negative integers i typed. Example: if i enter:

1,2,-3,3,-7,5,4,-1,4,5

the program should return me 3. I dont really have a clue, so please give me a hand :) PS. Sorry for my bad english, I hope you understand

Answer

Gareth Latty picture Gareth Latty · Apr 14, 2013

Break your problem down. Can you identify a way to check if a number is negative?

if number < 0:
    ...

Now, we have many numbers, so we loop over them:

for number in numbers:
    if number < 0:
        ...

So what do we want to do? Count them. So we do so:

count = 0
for number in numbers:
    if number < 0:
        count += 1

More optimally, this can be done very easily using a generator expression and the sum() built-in:

>>> numbers = [1, 2, -3, 3, -7, 5, 4, -1, 4, 5]
>>> sum(1 for number in numbers if number < 0)
3