我正在尝试编写线性搜索算法,用户必须在其中输入和搜索特定项目。在我的示例中,如果他们输入正确的单词,则代码将成功显示找到消息的消息。但是,如果我键入的单词不在列表中,则会给我一个错误。
wordlist = ['hello', 'goodbye', 'omg', 'test']
found = False
index = 0
search_item = input("Please type in the word that you would like to search")
while found == False:
if search_item == wordlist[index]:
print("Word found at index ", index)
found = True
else:
index = index + 1
if found == False:
print("Item not in list")
当我运行代码并键入不在列表中的单词时,出现此错误
if search_item == wordlist[index]: #check if the word the user typed matches the current item in the list
IndexError: list index out of range
您需要打破while循环->检查当前索引是否小于列表的大小index<len(wordlist)
。
尝试这个:
while found == False and index<len(wordlist):
if search_item == wordlist[index]:
print("Word found at index ", index)
found = True
else:
index = index + 1
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句