关于索引超出范围错误

时间:2016-05-12 11:22:14

标签: python indexing

def sum_squares(n):
    sum=0

    for i in range(1,len(n)+1):
        sum=0

        for j in range(1,n[i]):
            sum+=j**2

        print('The sum:',sum)
n=[2]
sum_squares(n)

在这里,我在第for j in range(1,n[i]):行收到错误 如果i-1有效,则需要i

2 个答案:

答案 0 :(得分:0)

i=len(n)时,n[i]确实会引发IndexError。您需要调整第一个范围:

for i in range(0, len(n)):

答案 1 :(得分:0)

数组索引从0开始,所以你应该这样做:

def sum_squares(n):
    sum=0

    for i in range(0,len(n)):
        sum=0

        for j in range(1,n[i]):
            sum+=j**2

        print('The sum:',sum)
n=[2]
sum_squares(n)