2015-10-16 48 views
1

我通过一段时间的条件运行我的定义,此时我只是希望它将列表中的所有数字打印出来,直到它达到列表的长度。IndexError:列表索引超出范围(打印整数)

然而,当我盖了,我得到了错误

"IndexError: list index out of rage"

我缺少什么?

numList = [5, 2, 21, 8, 20, 36, 1, 11, 13, 4, 17] 

def findHighest(intList): 
    iIndex = 0 
    iValue = intList[iIndex] 
    while iIndex != len(intList): 
      print(iValue) 
      iIndex = iIndex + 1 
      iValue = intList[iIndex] 

print(findHighest(numList)) 

我得到打印的名单,但随后编译器错误

+1

你只应该在'intList' – thefourtheye

回答

1

问题是,当iIndex是一个不到你加1索引列表。例如,如果您的列表大小为10,iIndex为9,则您将添加1到9,并且将iValue = intList [10]设置为越界,考虑列表是基于0的。

numList = [5, 2, 21, 8, 20, 36, 1, 11, 13, 4, 17] 

def findHighest(intList): 
    iIndex = 0 
    iValue = intList[iIndex] 
    while iIndex != len(intList)-1: 
     print(iValue) 
     iIndex = iIndex + 1 
     iValue = intList[iIndex] 

print(findHighest(numList)) 
+0

使用后,但是,因为我已经设置iIndex为0,开始时,我很困惑,为什么它不会工作了向增加索引!=,想必iIndex会增加到9,然后当它是==到9时,它会停止? – rawr105

+0

但是你的while循环条件是10的列表大小,所以基本上当循环去9然后增加1,这使得语句iValue = intList [10] – Maxqueue

+0

对,所以它不检查最后一个索引10码? (只是想确保我的理解是正确的) – rawr105

相关问题