Python 为什么我会得到“一个”;列表索引超出范围“;错误?

Python 为什么我会得到“一个”;列表索引超出范围“;错误?,python,indexoutofboundsexception,Python,Indexoutofboundsexception,这是我的节目: def FoundmovieNamesInQuery(userQueryPart,nameOfMovie): for userQueryPart in userQuery: for nameOfMovie in movieNames: if userQueryPart == nameOfMovie: return True return False

这是我的节目:

   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

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

其次,需要将参数传递给函数
FoundmovieNamesInQuery(userQuery,movieNames)


是不是应该是lines=file.readlines()?哇,这真的很管用。谢谢这样一个简单的错误让我第七天很头疼。一个初学者应该能够通过使用分治和
print(item)
调试来找出像这样的简单错误。下面是调试的基本指南。在这种情况下,我怀疑您有一行
不包含任何
字符。因此,您的
split
返回一个包含单个字符串的列表。
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
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")