pythonlistcountidentify

Python - Identify a negative number in a list


I need help doing a program which should receive 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.

How can I do it?


Solution

  • 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