Python return list not working for some reason

Question:

I’ve been trying to work on this assignment but for some reason the function I wrote won’t return the list I specified and throws a name 'numbers' is not defined error at me when printing the list outside the function.

def inputNumbers():
    try:
        initial_number_input = int(input("Please enter the first number: "))
    except ValueError:
        print("This is not a number.")
        return inputNumbers()
    else:
        numbers = []
        numbers.append(initial_number_input)
        if initial_number_input == 0:
            return numbers
        else:
            i = 0
            while True:
                try:
                    number_input = int(input("Please enter the next number: "))
                except ValueError:
                    print("This is not a number.")
                    continue
                else:
                    numbers.append(number_input)
                    i += 1
                    if number_input == 0:
                        break
            return numbers

inputNumbers()
print(numbers)

I’m still very new to programming so I am open to whatever suggestions you may have 😀

Note that if I print(numbers) above return numbers at the end of the function, it does print the list.

Thanks

Asked By: ElioChuk

||

Answers:

When you return a value from a function it needs to be assigned to something. At the moment you are returning numbers but nothing is using it.

To actually use the returned value your last 2 lines should be

numbers = inputNumbers()
print(numbers)

You can also just print the returned value without assigning it to a variable with

print(inputNumbers())
Answered By: Adam

you are printing print(numbers) outside the function inputNumbers().
if you want to go like this then you should assign the returned value from function like this

numbers = inputNumbers()
print(numbers)

or you just print the value instead of returning from the function

Answered By: Micky Rajkumar
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.