Drew Davis Drew Davis - 5 months ago 8
Python Question

What's wrong with my code? name is not defined?

Here I've defined a function that creates a list using the argument "number in list". I can use the function but when I try to print the list it says the variable isn't defined. Anytime I try to take the declared variables out of the defined function, it tells me local variable "i" referenced before assignment. Can someone help me get this code to work? Thanks!

def create_list(number_in_list):
i = 0
numbers = []
while i < number_in_list:
numbers.append(i)
i += 1


print "How many numbers do you want in your list?"
value = int(raw_input("> "))
create_list(value)


print "The numbers: "
print numbers
for num in numbers:
print num

Answer

Your numbers variable exists only in the function create_list. You will need to return that variable, and use the return value in your calling code:

Thus:

def create_list(number_in_list):
    i = 0
    numbers = []
    while i < number_in_list:
        numbers.append(i)
        i += 1
    return numbers     # <----

And in your main code:

numbers = create_list(value)