Home > OS >  How do I index a list to find a specific value and its location?
How do I index a list to find a specific value and its location?

Time:12-16

I am trying to write a code which will store movies on a list which I can retrieve by asking to add a movie either by its position or to check if it's on the list. So far, I have been working on the retrieving part, but I keep getting an error where "descriptor 'index' for 'list' objects doesn't apply to a 'str' object". This is my code so far

myFile = open("movies.txt", "a")
more = "yes"
while more.lower() == "yes":
    movie = input("Please enter a movie title: ")
    myFile.write(movie   '\n')
    more = input("Would you like another item? Enter 'yes' or 'no'. ")
    find = input("Would you like to find a movie? Enter 'yes' or 'no'. ")
    myFile.close()
    if find == "yes":
        myFile = open("movies.txt")
        xlist = list[myFile]
        f2 = input("What movie would like to find?")
        f3 = xlist.index(f2)
        print(f2   " is in number "   f3   " on the list")

CodePudding user response:

Explanation

In line number 11 of your code

xlist = list[myFile]

for making list of word that contain in file movies.txt you can do something like this

xlist=myFile.read().splitlines()

CODE

myFile = open("movies.txt", "a")
more = "yes"
while more.lower() == "yes":
    movie = input("Please enter a movie title: ")
    myFile.write(f'{movie}\n')
    more = input("Would you like another item? Enter 'yes' or 'no'. ")
    find = input("Would you like to find a movie? Enter 'yes' or 'no'. ")
    myFile.close()
    if find == "yes":
        myFile = open("movies.txt")
        xlist=myFile.read().splitlines()
        print(xlist)
        f2 = input("What movie would like to find?")
        f3 = xlist.index(f2)
        print(f'{f2}  is in number {f3} on the list')

OUTPUT

Please enter a movie title: money-heist
Would you like another item? Enter 'yes' or 'no'. no
Would you like to find a movie? Enter 'yes' or 'no'. yes
['Dark', 'money-heist']
What movie would like to find?Dark
Dark  is in number 0 on the list

CodePudding user response:

The problem is not in xlist but in f2, because input() returns string. If entering number 2, your line would look as if you wrote:

f3 = xlist.index("2")

Instead, cast input to integer:

try:
    f2 = int(input("What movie would like to find?"))
except ValueError:
    exit("Invalid number")

  • Related