【发布时间】:2019-10-01 19:48:41
【问题描述】:
我正在解决一个问题,我必须根据用户输入 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')
【问题讨论】:
标签: python python-3.x loops for-loop