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()
CodePudding user response:
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():
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.
CodePudding user response:
There is no need to create the list before you begin:
def user_answer():
user_answers=[]
print('\n')
for i in range(5):
print('\nPlease enter the answer to question', i 1, ':', sep=' ', end='')
user_answers.append(input())
return user_answers
CodePudding user response:
Your code return by calling the function, resulting in infinite loop. I guess what you mean is to return the variable user_answers not to return the function user_answers()
return user_answers
This might happen if you confuse function and variables with the same name. You might want to check function-and-variable-with-the-same-name
CodePudding user response:
This happens because you're returning the function itself which means you're creating a infinite recursive function.
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_answers
print(user_answer())
Try changing return user_answer() line to return user_answers
I hope you're trying to return the user answers array for further work.
