Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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]
     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()

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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():
     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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading