Search code examples
pythonnested-loops

Nested Loops calculation output is incorrect, but program runs


How am I able to get my program to display year 1 for the first 12 months and then year 2 for the next 12 months if the input value for years = 2?

Also I don't know where my calculation is going wrong. According to my desired output, the total rainfall output should be 37, but I am getting 39.

Added picture of current output. Total should be at 37 not 39. I also need the second batch of 12 months to say year 2

#the following are the values for input:
#year 1 month 1 THROUGH year 1 month 11 = 1
#year 1 month 12 THROUGH year 2 month 12 = 2

def main():
    #desired year = 2
    years = int(input("Enter the number of years you want the rainfall calculator to determine: "))
    calcRainFall(years)

def calcRainFall(yearsF):
    months = 12
    grandTotal = 0.0

    for years_rain in range(yearsF):
        total= 0.0
        for month in range(months):
            print('Enter the number of inches of rainfall for year 1 month', month + 1, end='')
            rain = int(input(': '))
            total += rain
        grandTotal += total
    #This is not giving me the total I need. output should be 37.
    #rainTotal = rain + grandTotal
    #print("The total amount of inches of rainfall for 2 year(s), is", rainTotal)
    print("The total amount of inches of rainfall for 2 year(s), is", grandTotal)
main()

Solution

  • I've shortened your code a little bit. Hopefully this is a complete and correct program:

    def main():
        years = int(input("Enter the number of years you want the rainfall calculator to determine: "))
        calcRainFall(years)
    
    def calcRainFall(yearsF):
        months = 12 * yearsF # total number of months
        grandTotal = 0.0     # inches of rain
    
        for month in range(months):
            # int(month / 12): rounds down to the nearest integer. Add 1 to start from year 1, not year 0.
            # month % 12: finds the remainder when divided by 12. Add 1 to start from month 1, not month 0.
            print('Enter the number of inches of rainfall for year', int(month / 12) + 1, 'month', month % 12 + 1, end='')
            rain = int(input(': '))
            grandTotal += rain
        print("The total amount of inches of rainfall for", yearsF, "year(s), is", grandTotal)
    
    main()