知道为什么这段代码不能按预期工作吗?

问题描述

这是我的第一个 python 代码。该代码应该向用户提示选项,然后根据用户输入执行操作。

但是,当我运行代码时,不是提示输入菜单,而是提示输入电影标题。这是我目前编写的代码

# 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

解决方法

当您创建一个值为函数的字典时,它会运行该函数来填充字典的值。所以这就是为什么它先运行 add_movie()

制作菜单的正确方法是这样的:

>>> def x():
...     print("hi")
... 
>>> y = {'a':x}
>>> y['a']()
hi

我们将字典的值保存为函数名,然后通过在返回值中添加 () 来调用它。