I thought that using the return function would cause the variable placed after it to be passed outside of my function (returned?). It appears not, why not?
I am trying to write some code that requires me to compile a list of 5 items inside a function, and then pass that list outside of the function and do some work with it. Right now I only have a print statement written outside of it, just trying to see if it's getting passed outside of my function but ill need to do more later on. It is telling me variable is undefined so I am assuming that it is not getting passed.
Why would a list variable placed after the return command not be passed outside of the function and be free to use, and what do I need to do to make it so that I can in fact call my list variable outside of the function?
#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)
A side note I need the function to not take any arguments so I can't use that method as a solution.
You need to save the returned value from get_name()
to a variable named user_list
outside of the scope of the function in order to print it:
#Storing the returned value from the function:
user_list = get_name()
print(user_list)
Without storing the return value, the function completes itself, returns the value up the stack where it is captured by nothing, and then it is subsequently dereferenced. The assignment of user_list
within the body of the function is only applicable inside of the scope of the function. As soon as it is returned, the program no longer 'sees' any variables named user_list
, which causes the print()
statement to fail.