我认为使用返回函数会导致放置在它之后的变量被传递到我的函数之外(返回?)。好像不是,为什么不呢?
我正在尝试编写一些代码,要求我在一个函数内编译一个包含 5 个项目的列表,然后将该列表传递到函数外部并对其进行一些处理。现在我只在它外面写了一个打印语句,只是想看看它是否在我的函数之外传递,但我以后需要做更多。它告诉我变量未定义,所以我假设它没有被传递。
为什么放置在 return 命令之后的列表变量不能传递到函数外部并可以自由使用,我需要做什么才能使它真正可以在函数外部调用我的列表变量?
#Gather data about elements and turn into a list to check agsint function list later
!curl https://raw.githubusercontent.com/MicrosoftLearning/intropython/master/elements1_20.txt -o elements1_20.txt
elements_20 = open("elements1_20.txt","r")
elements_20.seek(0)
elements = elements_20.readline().strip()
element_list = []
while elements:
element_list.append(elements)
elements = elements_20.readline().strip()
print(element_list)
# define function to get user input and compile it into a list
def get_name():
user_list = []
while len(user_list) < 5:
user_input=input("Name one of the first 20 items please kind sir: ")
#check to make sure the input is unique
if user_input.lower() in user_list:
print("please don't enter the same word twice")
else:
user_list.append(user_input.lower())
return user_list
get_name()
print(user_list)
旁注我需要函数不接受任何参数,所以我不能使用该方法作为解决方案。
最佳答案
您需要将 get_name()
的返回值保存到函数范围之外的名为 user_list
的变量中,以便打印它:
#Storing the returned value from the function:
user_list = get_name()
print(user_list)
在不存储返回值的情况下,该函数完成自身,将值返回到堆栈中,在那里它什么也没有捕获,然后它随后被取消引用。函数体内的 user_list
赋值仅适用于函数范围内。一旦返回,程序就不再“看到”任何名为 user_list
的变量,这会导致 print()
语句失败。
关于python - 如何将我的列表变量传回我的函数之外(Python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52023685/