python列出索引超出范围的错误-线性搜索代码

阿尔泰语

我正在尝试编写线性搜索算法,用户必须在其中输入和搜索特定项目。在我的示例中,如果他们输入正确的单词,则代码将成功显示找到消息的消息。但是,如果我键入的单词不在列表中,则会给我一个错误。

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
Rithin Chalumuri

您需要打破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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

代码中列出索引超出范围错误

Python:IndexError:修改代码后列出索引超出范围

python:代码中的列表索引超出范围错误

Python 排序和二分搜索索引错误:列表索引超出范围

线性判别分析(错误:索引1超出范围)

代码中的字符串索引超出范围错误

映射reduce的代码python,错误“字符串索引超出范围”

我的python代码异常“列表索引超出范围”

列出索引超出范围-索引错误Python

IndexError:列表索引超出范围(在 whoosh 搜索引擎库中)错误在

在简单的 python for 循环中列出索引超出范围错误

代码中的下标超出范围错误

在表格视图中使用搜索栏时,Swift致命错误索引超出范围

在搜索和滚动结果时快速在Tableview中获取索引超出范围错误

致命错误:索引超出范围,使用搜索栏 Swift 3 时

我在运行以下代码时出现索引超出范围错误

我如何无法从此代码获取列表索引超出范围错误?

如何修复此代码中的此错误?索引超出范围

执行以下代码时出现以下错误:索引超出范围

此斐波那契代码中的列表索引超出范围错误

蛇游戏错误代码(IndexError:列表索引超出范围)

代码在行上显示错误的输入和索引超出范围,我该如何修复它

Sklearn线性回归-“ IndexError:元组索引超出范围”

“搜索”是否导致“字符串索引超出范围”?(Python)

Python代码昨天运行良好,现在出现此“ IndexError:列表索引超出范围”

Instructables开源代码:Python IndexError:列表索引超出范围

Ahocorasick搜索树返回索引超出范围

IndexError:数组搜索中的列表索引超出范围

二进制搜索超出范围索引