Lack of iteration and appending of empty list

Viewed 34

The following code isn't iterating as it should. I don't understand what the problem is. Please advise if you think you might be able to help me.

def getRainfallAmounts(namesOfMonths):
    NUMBER_OF_MONTHS_IN_A_YEAR = 12
    totalRainfallList = [ ]
    
    for currentMonthIndex in range(NUMBER_OF_MONTHS_IN_A_YEAR):
        monthlyRainfall = float(input("Please enter the rainfall amount for " +\
                                      namesOfMonths[currentMonthIndex]))
        totalRainfallList.append(monthlyRainfall)
        
        return totalRainfallList
2 Answers

The return statement is indented under the for loop, so it returns at the end of the first iteration. You should un-indent it so the for loop completes and only then return:

def getRainfallAmounts(namesOfMonths):
    NUMBER_OF_MONTHS_IN_A_YEAR = 12
    totalRainfallList = [ ]
    
    for currentMonthIndex in range(NUMBER_OF_MONTHS_IN_A_YEAR):
        monthlyRainfall = float(input("Please enter the rainfall amount for " +\
                                      namesOfMonths[currentMonthIndex]))
        totalRainfallList.append(monthlyRainfall)
        
    return totalRainfallList # Here!

I will admit that I don't work much with python (what I'm assuming this is), but your return is in the body of the for loop, so you effectively finish the loop after (well, technically during) the first iteration.

Unindent the return by one level.

Related