pythonscrub1234
pythonscrub1234

Reputation: 63

How to get a while loop to start over after error?

would like to say I still feel fairly new too python in general. But I have a movie recommender system that I have been working on, and the way I have it setup is for the user to enter a movie in the console and then it spits out 10 recommendations and ask for another movie. When a misspelled movie is entered, it gives error message KeyError: 'Goodfellas' and it stops running. I would like for it to just start the loop over, until the user ends the loop using my break word. Here is my code for reference.

while True:
    user_input3 = input('Please enter movie title: ')
    if user_input3 == 'done':
        break
    print(get_input_movie(user_input3))

get_input_movie() is the function I am using to "select" the top 10 movies. Is this possible? Was not able to find much online. Thanks!

Also I am pulling data from a pandas dataframe and using TfidfVectorizer for my similarity.

Upvotes: 1

Views: 55

Answers (2)

Renan Lopes
Renan Lopes

Reputation: 411

To continue after an KeyError exception you should use a try block inside your loop, example:

try:
    ... # Here goes your code that can result in a KeyError exception
except KeyError:
    continue

Upvotes: 1

777moneymaker
777moneymaker

Reputation: 707

Look at try-except and continue:

while True:
    user_input3 = input('Please enter movie title: ')
    if user_input3 == 'done':
        break
    try:
        print(get_input_movie(user_input3))
    except KeyError:
        continue

Upvotes: 1

Related Questions