[英]Return list from while loop in a function?
I'm trying to return a list my_list
created within function make_list
to use in the function print_elems
. 我试图返回一个列表my_list
函数内创建make_list
在功能使用print_elems
。
I keep getting the error 我不断收到错误
my_list is not defined my_list未定义
for when I ask to print it, after calling "make_list". 当我要求打印它时,请调用“ make_list”。
What am I doing incorrectly in trying to return "my_list"? 在尝试返回“ my_list”时我做错了什么?
def make_list():
my_list = []
print("Enter \"-999\" to return list.")
x = int(input("Enter a number: "))
while x != -999:
my_list.append(x)
x = int(input("Enter a number: "))
return my_list
def print_elems(user_list):
print(user_list, sep=' ')
make_list()
print(my_list)
print_elems(my_list)
You are trying to access the local variable my_list
. 您正在尝试访问局部变量my_list
。 You have to use the returned value instead by assigning it to a variable: 您必须通过将返回值分配给变量来使用它:
some_name = make_list() # assign function result to variable
print(some_name)
print_elems(some_name)
On a side note, you probably want to slightly modify print_elems
: 附带一提,您可能需要略微修改print_elems
:
def print_elems(user_list):
print(*user_list, sep=' ')
The *
unpacks the list and passes its elements to the print
function. *
将列表解压缩 ,并将其元素传递给print
功能。 Otherwise, when passing a single positional argument to print
, the sep
parameter will never be used. 否则,当将单个位置参数传递给print
,将永远不会使用sep
参数。
You need to assign the return of your function to a variable: 您需要将函数的返回值分配给变量:
tata = make_list()
print(tata)
The variable my_list
is destroyed when you leave the scope of your function that defined it. 当离开定义它的函数的作用域时,变量my_list
被破坏。 That is why you return it. 这就是为什么您退还它。
See Short Description of the Scoping Rules? 请参阅范围规则的简短说明? and PyTut: Scopes and namespaces 和PyTut:作用域和名称空间
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.