-2

I have to set up two loops. One that keeps totaling the number of negative numbers in a list and is returned. Another that appends the negatives to a separate list to also be returned. I have only been able to return the first value in each loop.

# Given the parameter list, returns the count of negative numbers in the list
def num_negatives(list):
    negatives = 0
    for neg in list:
        if neg < 0:
            negatives += 1
            return negatives

# Given the parameter list, returns a list that contains only the negative numbers in the parameter list 
def negatives(list):    
    negList = []
    for negItems in list:
        if negItems < 0:
            negList.append(negItems)
            return negList    

# Prompts the user to enter a list of numbers and store them in a list
list = [float(x) for x in input('Enter some numbers separated by whitespace ').split()]
print() 

# Output the number of negatives in the list
print('The number of negatives in the list is', num_negatives(list))
print()

# output the list of negatives numbers    
print('The negatives in the list are ', end = '') 

for items in negatives(list):
    print(items, ' ', sep = '', end = '')     
print('\n')

If I were to put in the values 1 2 3 4 5 -6 7 -8 9 -12.7 at the start of the program, I should receive this.

The number of negatives in the list is 3

The negatives in the list are -6.0 -8.0 -12.7

Instead, I only get:

The number of negatives in the list is 1

The negatives in the list are -6.0
Akaisteph7
  • 5,034
  • 2
  • 20
  • 43
user294506
  • 23
  • 3

2 Answers2

2

You have your returns in the wrong locations. You don't want to return multiple times. You just want to return the final value once when your function is done running. So your functions should be like this:

# Find number of negative numbers in the list
def num_negatives(list):
    negatives = 0
    for neg in list:
        if neg < 0:
            negatives += 1
    return negatives

def negatives(list):    
    negList = []
    for negItems in list:
        if negItems < 0:
            negList.append(negItems)
    return negList       
Akaisteph7
  • 5,034
  • 2
  • 20
  • 43
0

I think you're searching for yield which is an elegant solution for creating iterables.

def num_negatives(list):
    negatives = 0
    for neg in list:
        if neg < 0:
            yield neg  # I return the negative number directly.

def negatives(list): 
    negList = []   
    negatives_generator = num_negatives(list)
    for negItem in negatives_generator:
        negList.append(negItem)
    return negList 

Then finally you can print the negatives list and len(negatives), you have both now.

For more details: What does yield do?

Ramy M. Mousa
  • 5,727
  • 3
  • 34
  • 45
  • While this is a useful tool, it does not address OP's situation, which appears to deal with a homework question that expects a specific approach. – Karl Knechtel Jul 14 '19 at 18:30