user3527972
user3527972

Reputation: 89

Creating multiple variables in a loop

I have a program that asks a user to come up with a question and then to type the answer. Right now I have it asking the user to type in 5 questions and answers. So basically it asks the user for a question and its answer 5 times. What I would really like it to do is ask the user for how many questions they would like to type and then based on that it presents the user with "type your question" and "type your answer" and stores those things as variables (i.e. "q1" and "a1" and repeating based on how many questions/answers they want to type) so I can then use these variables in a print statement later on in the program. I was thinking about using a while loop with a continue condition until and count down to 0 and then the loop ends but how do I constantly create new variables?

`   oneistart= raw_input('What is the first question: ')
oneiend= raw_input('What is the first answer: ')

Upvotes: 0

Views: 1407

Answers (2)

itzMEonTV
itzMEonTV

Reputation: 20339

I think, better than create dynamic variables in python, save it as list of dicts like.

lis = []
n = int(raw_input("How many? "))
for i in xrange(n):
    q = raw_input("enter q: ")
    a = raw_input("enter a: ")
    lis.append({"q"+str(i+1): q, "a"+str(i+1): a})
print lis
>>>[{'q1': 'ques1', 'a1': 'ans1'}, {'q2': 'ques2', 'a2': 'ans2'}]

Upvotes: 0

ha9u63a7
ha9u63a7

Reputation: 6814

How about working with a dictionary?

d = dict()  # Creates an empty dictionary

oneistart = raw_input('What is the first question: ')
oneiend = raw_input('What is the first answer: ')

d[oneistart] = oneiend  # updates the dictionary with new key-value (or updates existing value associated to a key

Also, if you call d.values() you will get a list of all your values (i.e. answers) and you can see how many answers you have got? There are also other functions associated to a dictionary object, which you can research on by reading the documentation (your task!).

Is this what you had in mind?

Upvotes: 1

Related Questions