Вопрос

I have problem with a nested loop problem. In a year, I want my loop to add up every number from the month of the year. When the year is over instead of adding the numbers from last year and adding it to the new year, i want it to begin again at 0.

Finally, it should show me the total of each year and give me an average of all the years.

Here is my sample if anyone could help me finish it:

total_rain = 0
month = 12
y = 0
rain = 0
month_rain = 0
years = int(input("How many years: "))

for y in range(years):
    y += 1
    print()
    print("In the year", y,"There will be:")

    for m in range(month):
        rain = float(input('How many inch of rainfall have fallen: ')) 
    total_rain += rain
    print(month_rain)
main() 

Every time a loop ends, it adds the number from the previous year. I want the new loop to start at 0 again and add up the numbers.

Это было полезно?

Решение

for y in range(years):
    y += 1
    for m in range(month):
        rain = float(input('How many inch of rainfall have fallen: '))
        total_rain += rain
    print("In the year", y,"There will be:", total_rain," inches of rain")
    #reset variable
    total_rain = 0

First of all, I corrected the indentation of "total_rain += rain" because you had it nested outside of the 2nd for loop, therefore it wouldn't actually add the rain you input each time.

Then all I did was set the total rain to 0 to reset it.

It works like a charm and is very similar to your own code.

Другие советы

total_rain = []
months = 12
years = int(input("How many years: "))
for y in range(1, years+1):
    print("In the year", y,"There will be:")
    annual_rain = []
    for m in range(1,13):
        rain = float(input('How many inch of rainfall have fallen in month %s: ' %m))
        annual_rain.append(rain)
    total_rain.append(annual_rain)

for y,year in enumerate(total_rain, 1):
    print("Total rain in year %s: %s. Average monthly rain: %s" %(y, sum(year), sum(year)/len(year)))
total_rain = 0
month = 12
rain = 0
years = int(input("How many years: "))

for y in range(years):
    month_rain = 0
    print()
    print("In the year", y,"There will be:")

    for m in range(month):
        rain = float(input('How many inch of rainfall have fallen: ')) 
        month_rain += rain
    total_rain += month_rain
    print("year %s: %s" % (y, month_rain) )
print("total rain: %s" % (total_rain/years))
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top