如何运行for循环,然后在最后进行计算

时间:2019-10-01 19:48:41

标签: python python-3.x loops for-loop

我正在解决一个问题,我必须根据用户输入的number of years和用户输入的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')

2 个答案:

答案 0 :(得分:3)

在进入for循环之前声明total,以免每次迭代都将其重置,将y年的降雨总量添加到total的每次迭代中,然后计算并打印您的退出循环后的结果。像这样:

# 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.' )

答案 1 :(得分:0)

尝试使用数据结构,在这种情况下,我建议创建一个列表来存储所有值,并在for循环之前实例化它。然后它在for循环之后仍然存在,您可以进行计算。