2017-07-27 40 views
-1

我試圖驗證每個元素,因爲它是輸入,以確保沒有名稱小於2位數。我假設只有2個字符不存在名稱。空格或姓氏不重要。在Python中驗證列表元素

我收到列表索引超出範圍錯誤。

#The getValidateNames function takes 20 names as input,validates them, sorts list and returns list. 
def getValidateNames(): 
    nameList = [] #Create empty list variable. 
    counter = 1  #Loop counter 

    #Loop through and prompt for 20 names. 
    while counter <=20: 
    nameList.append(input("Please enter name #{}:".format(counter))) 
    if nameList[counter] < 2: 
     print("You have entered an invalid name.") 
     nameList.append(input("Please try again: ")) 
    counter += 1 

    nameList.sort() 
    return nameList 
+0

爲什麼在測試之前追加?如果不是其他方式。 –

+0

使用'len()'函數檢查'string'的大小,使名稱輸入一個變量來存儲它,然後檢查它的大小 –

+0

列表索引從零開始。但是counter - 你用來索引'nameList'的變量 - 最初設置爲'1'。 –

回答

0

列表索引在Python中從零開始。所以nameList的第一個索引是0而不是1。因此,由於您初始化了counter1,然後嘗試索引nameList,Python提出了IndexError

但是,您的代碼仍然存在問題。做nameList[counter] > 2沒有比較nameList中索引counter的字符串長度。它只是將字符串本身與整數2進行比較,這實際上沒有意義。您需要使用len()內置函數來獲取字符串的長度:

counter = 0 

while counter <=20: 
    ... 
    if len(nameList[counter]) < 2: 
     ... 
    ...