-3

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
Mangohero1
  • 1,832
  • 2
  • 12
  • 20
  • 2
    Indent correctly, indent the function body – Andrew Li Jul 03 '16 at 20:13
  • first, can you fix your indentation in the question? It is not easy to tell where it is. if you create `numbers` in your `create_list` it will not be in the same namespace/scope. and will not be accessible outside of the function. – Tom Myddeltyn Jul 03 '16 at 20:15
  • 1
    Python depends on correct indentation. Most other languages don't. Most other languages just become unreadable messes if you don't indent. – Nic Jul 03 '16 at 20:22
  • My apologies about the indentation error. Some reason the code did not paste correctly with indentation in mind. – Mangohero1 Jul 03 '16 at 20:28

1 Answers1

3

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)
C. K. Young
  • 219,335
  • 46
  • 382
  • 435