Im trying to create code that will choose a random number and then use that number to put the content of specific lines in a text file into a list.
I don't want a question to be added to the list more than once, so I made another list that would contain all the numbers that have been chosen. All the questions are on odd lines, and the answers are on even lines, so the generated number must also be even.
The code below is what I've tried to do, which doesn't run.
import random
#the empty question list
qlist=[0,0,0,0,0]
#the list that is filled with question numbers that have already been chosen
noschosen=[]
file=open('questiontest.txt')
lines=file.readlines()
i=0
#random question chooser
while i<len(qlist):
chosen=False
n=random.randint(1,10)
for index in range(0,len(noschosen)):
if n==noschosen[index]:
chosen=True
#all questions are on odd lines, so the random number can't be even.
while n%2==0 or chosen==True:
n=random.randint(1,10)
#the number chosen is added to the chosen list
noschosen.append(n)
#the program adds the question and its answer to qlist
qlist[i]=(lines[n],lines[n+1])
#increment
i=i+1
print (qlist)
This is what's in the next file:
.
Question1
Answer1
Question2
Answer2
Question3
Answer3
Question4
Answer4
Question5
Answer5
Question6
Answer6
Question7
Answer7
Question8
Answer8
Question9
Answer9
Question10
Answer10
The dot on the first line is intentional.
I expect the program to fill the list randomly in this fashion:
[('QuestionA', 'AnswerA'),
('QuestionB', 'AnswerB'),
('QuestionC', 'AnswerC'),
('QuestionD', 'AnswerD'),
('QuestionE', 'AnswerE')]
The letters A. B. C, D and E represent any of the numbers from 1 to 10. For example, if the first n turned out to be 5, "Question3" and "Answer3" would be put into the first place (since line 5 is where Question3 is).
The Question number and its corresponding Answer should be grouped together. I'm not sure why my current code doesn't work, can anyone see the problem or how I could improve this code in general?