为什么会出现“列表索引超出范围”错误?

2024-04-26 13:59:40 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的程序:

   def FoundmovieNamesInQuery(userQueryPart,nameOfMovie):
        for userQueryPart in userQuery:
            for nameOfMovie in movieNames:
                if userQueryPart == nameOfMovie:
                    return True
        return False


    print("welcome")
    userQuery = input("use our quick search to find cinema times for films shwing today: ").lower().split()
    print(userQuery)

    with open("movies.txt")as file:
        lines = file.readline()
    slutionFound = False

    for line in lines:
        item = line.split(":")
        movieNames = item[0].split()
        movieTimes = item[1]
        if FoundmovieNamesInQuery():
            print(movieTimes)
            solutionFound = True
    if solutionFound == False:
        print("movie not found.\n please call us on 0800 020 030")

但当我运行它时,它会给出以下错误消息:

welcome
use our quick search to find cinema times for films shwing today: annabelle
['annabelle']
Traceback (most recent call last):
  File "C:\Users\FARUQE TALUKDAR\Downloads\online film.py", line 20, in <module>
    movieTimes = item[1]
IndexError: list index out of range

这是我的文本文件:

run along : this movie will be showing at 18.00
annabelle : this movie will be showing at 13.00
x-men : this movie will be showing at 7.00

Tags: infalseforiflinemoviethisitem
1条回答
网友
1楼 · 发布于 2024-04-26 13:59:40

首先,您需要使用readlines而不是使用readline,它将读取整个txt。你知道吗

其次,需要将参数传递给函数FoundmovieNamesInQuery(userQuery, movieNames)。你知道吗

def FoundmovieNamesInQuery(userQueryPart,nameOfMovie):
        for userQueryPart in userQuery:
            for nameOfMovie in movieNames:
                if userQueryPart == nameOfMovie:
                    return True
        return False


print("welcome")
userQuery = input("use our quick search to find cinema times for films shwing today: ").lower().split()
print(userQuery)

with open("movies.txt")as file:
    lines = file.readlines()
solutionFound = False

for line in lines:
    item = line.split(":")
    movieNames = item[0].split()
    movieTimes = item[1]
    if FoundmovieNamesInQuery(userQuery, movieNames):
        print(movieTimes)
        solutionFound = True
if solutionFound == False:
    print("movie not found.\n please call us on 0800 020 030")

相关问题 更多 >