如何打印电影列表?是否必须将列表放在函数之外?我试图将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)在此处输入代码
发布于 2019-12-09 08:58:44
是的,它确实需要在函数之外。这与作用域有关。在代码块中创建的任何变量都只能从该块中访问。函数是一种代码块,因此一旦您离开该函数,add_movie()中的movies = []就会被删除。但是,如果您将声明movies = []放在函数外部,那么当函数离开时,值不会被删除,我认为这是您想要的行为。
另一种选择是从add_movie()和menu()返回movies的值
发布于 2019-12-09 12:04:50
函数内部的变量不能在该函数外部访问,除非返回该变量。
这是所谓作用域的一部分,作用域是代码中可以和不能访问变量的地方。
对于你的情况,你有几个选择,下面是我认为最简单的:
我去掉了你的一些代码行来编译它,因为我没有你的其他函数
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)https://stackoverflow.com/questions/59241268
复制相似问题