首页 > 解决方案 > 如何运行for循环然后在最后进行计算

问题描述

我正在解决一个问题,我必须根据 user-inputnumber of years和 user-input计算平均降雨量inches of each month

我想做的是:

计算每年的总计和最后的平均值,而不是在 for 循环的每次迭代中都这样做,我对如何做到这一点持空白。

这是我的代码:

MONTHS = 12
total = 0.0

while True:
  try:
    years_of_rain = int(input('How many years of rainfall would you like to calculate?: '))

    if years_of_rain <= 0 :
        print('Invalid data. You must enter 1 or more years. Try again.')
        continue

    for y in range(years_of_rain) :
        jan = float(input('How many inches of rain fell in January of year ' + str(y + 1) + '?: '))
        feb = float(input('How many inches of rain fell in February of year ' + str(y + 1) + '?: '))
        mar = float(input('How many inches of rain fell in March of year ' + str(y + 1) + '?: '))
        apr = float(input('How many inches of rain fell in April of year ' + str(y + 1) + '?: '))
        may = float(input('How many inches of rain fell in May of year ' + str(y + 1) + '?: '))
        jun = float(input('How many inches of rain fell in June of year ' + str(y + 1) + '?: '))
        jul = float(input('How many inches of rain fell in July of year ' + str(y + 1) + '?: '))
        aug = float(input('How many inches of rain fell in August of year ' + str(y + 1) + '?: '))
        sep = float(input('How many inches of rain fell in September of year ' + str(y + 1) + '?: '))
        oct = float(input('How many inches of rain fell in October of year ' + str(y + 1) + '?: '))
        nov = float(input('How many inches of rain fell in November of year ' + str(y + 1) + '?: '))
        dec = float(input('How many inches of rain fell in December of year ' + str(y + 1) + '?: '))

        rain_average_calc = (jan + feb + mar + apr + may + jun + jul + aug + sep + oct + nov + dec) / MONTHS
        total += jan + feb + mar + apr + may + jun + jul + aug + sep + oct + nov + dec

        num_months = MONTHS * years_of_rain

        average = total / num_months

        print('The total amount of rain was ' + format(total , ',.2f') + ' inches' )
        print('the average amount of rain was ' + format(rain_average_calc , ',.1f') + ' inches per month.' )
        print(average)
        print(num_months)

    break
except:
    print('invalid. try again')

标签: pythonpython-3.xloopsfor-loop

解决方案


在进入 for 循环之前声明total它不会在每次迭代中重置,将一年的总降雨量添加ytotal每次迭代中,然后在退出循环后计算并打印结果。像这样的东西:

# Outside of for loop
total = 0

for y in range(years_of_rain):
     # Inside of for loop

     # Code for getting input for current year goes here

     total += jan + feb + mar + apr + may + jun + jul + aug + sep + oct + nov + dec

# Outside of for loop, after it has finished

num_months = MONTHS * years_of_rain
average = total / num_months

print('The total amount of rain was ' + format(total , ',.2f') + ' inches' )
print('the average amount of rain was ' + format(average , ',.1f') + ' inches per month.' )

推荐阅读