Reputation: 1
This is my first python code. The code is supposed to prompt user with options and then perform actions based on the user input.
However, when I run the code, instead of prompting for the menu I get the prompt to enter the movie title. Here's the code I have written so far.
# code starts here
MENU_PROMPT = "\nEnter 'a' to add a movie, 'l' to see your movies, 'f' to find your movie or 'q' to quit: "
movies = []
def add_movie():
title = input("Enter the movie title: ")
director = input("Enter the movie director: ")
year = input("Enter the movie year: ")
movies.append({
'title': title,
'director': director,
'year': year
})
def show_movies():
for movie in movies:
print_movie(movie)
def print_movie(movie):
print(f"Title : {movie['title']}")
print(f"Director : {movie['director']}")
print(f"Release Year : {movie['year']}")
def find_movie():
search_title = input("Enter movie title you are looking for: ")
for movie in movies:
if movie["title"] == search_title:
print_movie(movie)
user_options = {
"a" : add_movie(),
"l" : show_movies(),
"f" : find_movie()
}
def menu():
selection = input(MENU_PROMPT)
while selection != "q":
if selection in user_options:
selected_function = user_options[selection]
selected_function()
else:
print('Unknown command, Please try again')
selection = input(MENU_PROMPT)
menu()
#code ends here
Upvotes: 0
Views: 49
Reputation: 4489
When you create a dictionary with a value being a function, it will run that function to fill in the value of the dictionary. So that is why it is running add_movie()
first before anything else.
The proper way to do your menu would be like this:
>>> def x():
... print("hi")
...
>>> y = {'a':x}
>>> y['a']()
hi
We save the value of the dictionary as the function name, then call it by adding the ()
to the returned value.
Upvotes: 1