Why did I get an infinite loop (python)?

I’m new to programming.
I’m trying to write a program with 3 lists.
There are no while loops in the code (see below).

I tried saving the user’s answers in a list called ‘user_answers’.
The for loop is supposed to loop only 5 times (which is the length of the list), but it seems like I got an infinite loop instead.
Any insight on how to fix this?

def user_answer():
     user_answers=[0, 0, 0, 0, 0]
     for i in range (len(user_answers)):
         print('\nPlease enter the answer to question', i+1, ':', sep=' ', end='')

     return user_answer()

>Solution :

Because you return that function name user_answer() that makes it running recursive indefinitely.

Therefore, you should do return user_answers instead of return user_answer().

If you want to make the array having exact size=5, you can loop it 5 times instead of mutating the array every time. You can put the instruction for user input in the input() as well. This will make your code more simple. You can try this example:

def user_answer():
     for i in range(5):
         user_answers.append(input("Please enter the answer to question "+str(i+1)+": "))

     return user_answers

P.S. If you want to have 3 lists that each contains 5 elements, you can call the function user_answer() 3 times or putting it in a loop.

Leave a Reply