为什么我的列表索引超出范围?

时间:2015-10-15 05:17:38

标签: python python-3.x

def main():
    print("You haved activated Weather Pro 3.0")
    rain_inputs()
    rain_calc()

def rain_inputs():
    global rain
    rain = []
    for x in range(1, 13):
        try:
            rain_meter = float(input("What is the rainfall? "))
            rain.append(rain_meter)
            if x == 4:
                print("8 more months to go!")
            elif x == 7:
                print("5 more months to go!")
            elif x == 9:
                print("2 more to go! Smash those keys!")
            elif x == 13:
                return
        except Exception as err:
            err = ("You should be putting in numbers!")
            print(err)

rain_calc应该计算所有列出的输入的总和。

def rain_calc():
    rain_math =(rain[0] + rain[1] + rain[2] + rain[3])
    rain_math2 =(rain[5] + rain[6] + rain[7] + rain[8])
    rain_math3 =(rain[9] + rain[10] + rain[11] + rain[12])
    rain_total =(rain_math + rain_math2 + rain_math3)
    print(rain_total)   

main()   

错误发生在rain-math3

Programming/RainFall.py", line 30,           in rain_calc rain_math3 =(rain[9] + rain[10] + rain[11] + rain[12])
IndexError: list index out of range

1 个答案:

答案 0 :(得分:2)

rain[12]超出范围,因为rain只有12个元素。你错过了rain[4],所以你可能想要这个:

def rain_calc():
    rain_math =(rain[0] + rain[1] + rain[2] + rain[3])
    rain_math2 =(rain[4] + rain[5] + rain[6] + rain[7])
    rain_math3 =(rain[8] + rain[9] + rain[10] + rain[11])
    rain_total =(rain_math + rain_math2 + rain_math3)
    print(rain_total)