我试着验证输入的每个元素,以确保没有少于2位数字的名称。我假设不存在只有两个字符的名字。空格或姓无关紧要。在
我得到一个列表索引超出范围错误。在
#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
在Python中,列表索引从零开始。所以}。因此,因为您将
nameList
的第一个索引是0
,而不是{counter
初始化为1
,然后尝试索引nameList
,Python引发了一个IndexError
。在但是,您的代码仍然存在问题。做
nameList[counter] > 2
不是比较nameList
中索引counter
处的字符串长度。它只是简单地将字符串本身与整数2
进行比较,这实际上没有意义。您需要使用len()
内置函数来获取字符串的长度:相关问题 更多 >
编程相关推荐