在python中创建一个显示降雨量的程序

时间:2014-04-23 02:57:50

标签: python list python-3.x

我应该创建一个程序,使用特定的降雨量数字(不要求用户输入数字)来输出每个月的降雨量,平均值,总数,最小值和最大值。我的程序应该是这样的:

Austin Tx Rainfall 2009

Jan    0.40

Feb    0.94

Mar    3.21

Apr    3.74

May    1.73

Jun    1.03

Jul    1.27

Aug    2.58

Sep    6.98

Oct    6.90

Nov    2.80

Dec      2.53

Total   34.11

Average 2.84

Max    6.98

Min    0.40

这是我到目前为止所做的:

amount = []
total = 0
month = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']
am =[0.4,0.94,3.21,3.74,1.73,1.03,1.27,2.58,6.98,6.9,2.8,2.53]
for j in range(len(am)):
    total+=j
print('Austin Tx Rainfall 2009')
print ("Month\t\tTotal Rainfall")
for i in range(len(month)):
    print (month[i], "\t\t", amount[i])
#total
print ("Total:\t\t ", total)
#average
average = total/12
print ("Average:\t",average)
min=min(am)
max=max(am)
print("min:\t",min)
print("max:\t",max)

但是,当我运行它时,它会返回:

print (month[i], "\t\t", amount[i])
IndexError: list index out of range

非常感谢任何帮助。 *另一个问题,当我尝试添加降雨量时,总积累了指数,所以总数变为66(0 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 + 11 )。如何获得添加实际数据的总数?

3 个答案:

答案 0 :(得分:2)

您的amount为空。你可能想要

print (month[i], "\t\t", am[i])

答案 1 :(得分:1)

您的金额列表为空 你的总数应该是这样的:

表示范围内的j(len(am)):     total = total + am [j]

答案 2 :(得分:1)

进行一些改写:

COLUMNS = "{:<12} {:>4}".format

months  = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']
amounts = [0.4,0.94,3.21,3.74,1.73,1.03,1.27,2.58,6.98,6.9,2.8,2.53]

def main():
    print('Austin Tx Rainfall 2009')

    print(COLUMNS("Month", "Total Rainfall"))
    for month, amount in zip(months, amounts):
        print(COLUMNS(month, amount))

    print(COLUMNS("Total:", sum(amounts)))
    print(COLUMNS("Average:", sum(amounts) / len(amounts)))
    print(COLUMNS("Min:", min(amounts)))
    print(COLUMNS("Max:", max(amounts)))

main()

给出了

Austin Tx Rainfall 2009
Month        Total Rainfall
Jan           0.4
Feb          0.94
Mar          3.21
Apr          3.74
May          1.73
Jun          1.03
Jul          1.27
Aug          2.58
Sep          6.98
Oct           6.9
Nov           2.8
Dec          2.53
Total:       34.11
Average:     2.8425
Min:          0.4
Max:         6.98