我正在处理一个作业,并完成了作业,但想查看是否有一种方法可以利用enter_rainfall下的月份列表。当我输入询问用户的降雨量时,我想知道是否可以在索引末尾添加months_list,并让索引为每次迭代添加一个。代码如下:
def main():
months_list = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
rain = enter_rainfall()
average = avg_rainfall(rain)
low_high = low_High(rain, months_list)
def enter_rainfall():
rain_fall = []
months = 12
for month in range(months):
rain_amount = float(input('Please enter the amount of rainfall for each month:'))
rain_fall.append(rain_amount)
return(rain_fall)
def avg_rainfall(rain):
total = 0
for value in rain:
total += value
average = total / len(rain)
print('The total rainfall for the year is', total, 'inches')
print('The average monthly rainfall is', format(average, '.2f'), 'inches')
return(average)
def low_High(rain, months_list):
low_val = min(rain)
low_month = months_list[rain.index(low_val)]
high_val = max(rain)
high_month = months_list[rain.index(high_val)]
print('The month with the highest rainfall is', high_month)
print('The month with the lowest rainfall is', low_month)
main()
答案 0 :(得分:1)
最好的方法是将月份传递到输入函数中。不要使用全局变量。
def main():
months_list = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
rain = enter_rainfall(months_list)
average = avg_rainfall(rain)
low_high = low_High(rain, months_list)
def enter_rainfall(months):
rain_fall = []
for month in months:
rain_amount = float(input('Please enter the amount of rainfall for {month}:'.format(month=month)))
rain_fall.append(rain_amount)
return(rain_fall)