Python 名称';电影';如果未定义,请在函数内打印列表

Python 名称';电影';如果未定义,请在函数内打印列表,python,Python,如何打印电影列表 我必须把列表放在函数之外吗? 我试着把电影变量放在函数外,电影列表被打印出来,我必须把它放在函数外吗 def menu(): user_input = input('inter "a" to add a movie, "i" to show a movie, "f" to find a movie, "q" to stop ') while user_input != 'q': if user_input == 'a':

如何打印电影列表 我必须把列表放在函数之外吗? 我试着把电影变量放在函数外,电影列表被打印出来,我必须把它放在函数外吗

def menu():
    user_input = input('inter "a" to add a movie, "i" to show a movie, "f" to find a movie, "q" to stop  ')
    while user_input != 'q':
        if user_input == 'a':
            add_movie()
        elif user_input == 'i':
            show_movie()
        elif user_input == 'f':
            find_movie()
        else:
            print('unknown command')
        user_input = input('inter "a" to add a movie, "i" to show a movie, "f" to find a movie, "q" to stop  ')


def add_movie():
    movies = [] `if i moved this variable out the function it get printed`
    name = input('what is movie name? ')
    date = int(input('date of movie? '))
    dirctor = input('directer name? ')

    movies.append({
        'name': name,
        'data': date,
        'dirctor': dirctor
    })


menu()
print(movies)

在此处输入代码

是,它确实需要在函数外部。这与范围有关。在代码块内创建的任何变量都只能从该块内访问。函数是代码块的一种类型,因此您在
add_movie()
中拥有的
movies=[]
将在您离开函数后立即删除。但是,如果将声明
movies=[]
放在函数外部,则函数离开时不会删除这些值,我认为这是您想要的行为


另一个选项是从
add_movie()
menu()

返回
movies
的值,函数内部的变量不能在该函数外部访问,除非您返回它

这是所谓作用域的一部分,作用域是代码中可以和不能访问变量的位置

对于您的情况,您有一些选择,以下是我认为最简单的:

我取出了你的一些行来编译它,因为我没有你的其他函数


您还可以在menu()中定义它,然后将它传递给add_movie,然后返回它,然后从menu()返回它
def menu():
    user_input = input('inter "a" to add a movie, "i" to show a movie, "f" to find a movie, "q" to stop  ')
    while user_input != 'q':
        if user_input == 'a':
            movies = add_movie()    # Change made here
        else:
            print('unknown command')
        user_input = input('inter "a" to add a movie, "i" to show a movie, "f" to find a movie, "q" to stop  ')
    return movies    #Change made here


def add_movie():
    movies = []
    name = input('what is movie name? ')
    date = int(input('date of movie? '))
    dirctor = input('directer name? ')
    movies.append({'name': name, 'data': date, 'dirctor': dirctor})
    return movies    # Change made here


movies = menu()    # Change made here
print(movies)