未定义名称“movies”,请在函数内打印列表

2024-07-01 07:57:46 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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)

在此处输入代码


Tags: to函数nameadd列表inputdate电影
2条回答

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

另一个选项是从add_movie()menu()返回movies的值

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

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

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

我把你的一些行拿出来编译,因为我没有你的其他函数

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)

相关问题 更多 >

    热门问题