r/AskProgramming • u/Cold_Abrocoma7320 • Oct 11 '26
For loop
How would I store 3 different answers to the same 3 questions asked using a for loop. I know how to store one answer, but not all three while still using the for loop
0
Upvotes
5
u/OneMathematician1757 Oct 11 '26 edited Oct 11 '26
You need to instantiate a data structure outside the scope of the loop in order to retain the data between the loop iterations. There are various data structures to hold multiple data elements as the other commenters have shown.
4
u/naomimyselfandi Oct 11 '26
I'd need some more context for what you're doing to really answer this. Is your setup something like this?
Or if you're using Python:
3
u/Previous-Mail7343 Oct 11 '26
An array, or a collection of some kind depending on what you are storing and how you are using it
3
u/iOSCaleb Oct 11 '26
Keep in mind that you don’t always have to use a loop. It might make more sense to write a function that asks a question snd returns an answer, and then call that once for each question, doing whatever you want with each answer.
If you do want to use a loop, look for a way to work the same way with each answer. For example, you could store the answers in a dictionary using the questions as keys.
3
u/Different_Pain5781 Oct 11 '26
Just use an array.
3
u/burhop Oct 11 '26
I admire your determination not to use AI.
1
u/Forward_Problem_8982 Oct 11 '26
You have a container like a list outside the loop. Every time you get an answer inside the loop, you put it to the end of the list. After the loop, all your answers are in the list in the order that you put them in.
1
u/unapologeticjerk Oct 12 '26
Bonus question for thread:
Can this be done using comprehension in Python?
1
u/faultydesign Oct 11 '26
A hashmap/dictionary id say
But are you sure it’s the correct approach?
0
u/hk4213 Oct 11 '26
Form group or object. Loop through the object keys and submit the object to be saved.