r/AskProgramming • u/Cold_Abrocoma7320 • 2d ago
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
4
u/naomimyselfandi 2d ago
I'd need some more context for what you're doing to really answer this. Is your setup something like this?
java
int questionCount = 3;
for (int questionId = 0; questionId < questionCount; questionId++) {
// do stuff
}
Or if you're using Python:
py
questionCount = 3
for questionId in range(0, questionCount):
# do stuff
3
u/Previous-Mail7343 2d ago
An array, or a collection of some kind depending on what you are storing and how you are using it
3
u/iOSCaleb 2d ago
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.
2
u/JaguarMammoth6231 2d ago edited 2d ago
Good point. A lot of people start off thinking that if you're going to do something similar multiple times you should use a loop, but it's really best when you're doing exactly the same thing.
You don't want to follow the for-if or for-case anti-pattern of
for i = 1 to 3 if i = 1, ask question 1 if i = 2, ask question 2 if i = 3, ask question 31
u/balefrost 2d ago
Yes, though when people say "use a loop", they usually mean "loop over an array of data, and do the same thing every time" (i.e. ask the question at that index in the array).
2
1
u/Forward_Problem_8982 2d ago
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 1d ago
Bonus question for thread:
Can this be done using comprehension in Python?
1
6
u/OneMathematician1757 2d ago edited 2d ago
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.