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] print('\n') for i in range (len(user_answers)): print('\nPlease enter the answer to question', i+1, ':', sep=' ', end='') user_answers[i]=input() return user_answer()
Because you return that function name
user_answer() that makes it running recursive indefinitely.
Therefore, you should do
return user_answers instead of
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(): user_answers= for i in range(5): user_answers.append(input("Please enter the answer to question "+str(i+1)+": ")) print() return user_answers print(user_answer())
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.