-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
爲什麼在測試之前追加?如果不是其他方式。 –
使用'len()'函數檢查'string'的大小,使名稱輸入一個變量來存儲它,然後檢查它的大小 –
列表索引從零開始。但是counter - 你用來索引'nameList'的變量 - 最初設置爲'1'。 –