Piegoose
Piegoose

Reputation: 43

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.

I keep getting the error

my_list is not defined

for when I ask to print it, after calling "make_list".

What am I doing incorrectly in trying to return "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)

Upvotes: 0

Views: 1482

Answers (2)

user2390182
user2390182

Reputation: 73450

You are trying to access the local variable 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:

def print_elems(user_list):
    print(*user_list, sep=' ')

The * unpacks the list and passes its elements to the print function. Otherwise, when passing a single positional argument to print, the sep parameter will never be used.

Upvotes: 3

Patrick Artner
Patrick Artner

Reputation: 51623

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. That is why you return it.


See Short Description of the Scoping Rules? and PyTut: Scopes and namespaces

Upvotes: 1

Related Questions