2015-10-16 77 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

相關問題