2013-12-12 238 views
1

該程序應該要求用戶輸入12個月的月降雨量,計算並計算年度降雨量,月平均降雨量和最高和最低量月份的總和。使用列表獲得平均值

我可以得到它要求輸入,給每年總和平均每月,但我覺得好像程序的輸入部分應該減少某種方式,它看起來太大,笨重,我不能完全弄清楚如何獲得高/低的平均值。 任何幫助將不勝感激。 在此先感謝。

def main(): 
    jan = int(input('Enter Rainfall For January: ')) 
    feb = int(input('Enter Rainfall for February: ')) 
    mar = int(input('Enter Rainfall For March: ')) 
    april = int(input('Enter Rainfall For April: ')) 
    may = int(input('Enter Rainfall For May: ')) 
    june = int(input('Enter Rainfall For June: ')) 
    jul = int(input('Enter Rainfall For July: ')) 
    aug = int(input('Enter Rainfall For August: ')) 
    sept = int(input('Enter Rainfall For September: ')) 
    oct = int(input('Enter Rainfall For October: ')) 
    nov = int(input('Enter Rainfall For November: ')) 
    dec = int(input('Enter Rainfall For Deceember: ')) 
    totalyear = jan + feb + mar + april + may + june + jul + aug + sept + oct + nov + dec 
    print('The total for the year is: ',totalyear) 
    avg = jan + feb + mar + april + may + june + jul + aug + sept + oct + nov + dec/12 
    print('The average monthly rainfall is: ',avg) 
main() 

回答

6

您可以使用列表和循環。 :)

def main(): 
    months = ["Jan","Feb" .... ,"Dec"] 
    rain = [] 
    for month in months: 
     rain.append(int(input("Enter .. for" + month))) 
    print("Total", sum(rain)) 
    print("Average", sum(rain)/float(len(rain))) 

同樣地,最大值和最小值,您可以使用max(rain)min(rain)