BlizzardGizzard BlizzardGizzard - 6 months ago 12
Python Question

How to create a loop that makes a new input over and over again?

I want to make a for loop that keeps asking for a new input that has a different name each time so it would be q1, q2, q3, q4, etc. That way I don't have to keep making more inputs or a specified amount of them.

I also need it to print the same question on each input.

E.g. "What would you like to add to your soup.

Thanks for any help I can get.

Answer

In order to store an indeterminate number of responses to your questions, you should use a list. Create an empty list before beginning your for loop and use the list.append() function to add each answer to your list as you go.

A list has the advantage of being relatively memory efficient. Using a dictionary requires you to save key-value pairs (using twice as much memory) instead of simply relying on the order of values in memory.

Sample code might look like this:

n = 10 %the number of iterations to perform
answers = list()
for i in range(0, n):
     answers.append(input("question?"))

print(answers[2]) %this would print the third entered answer
print(answers[4]) %this would print the fourth entered answer
Comments