how can access to two element in one loop - python

Viewed 39

access next index in loop

I've got a text file containing the following lines:

what's you'r name?
my name is Micheal
how old are you?
I'm 33 year's old
filename= input("file name?\n")

try:
    txt = open(filename+'.txt', 'r', encoding='utf-8').readlines()
    print('could not find file name')
except FileNotFoundError:
    print('could not fine file')

for count, line in enumerate(txt):
    pass

for i in range(count+1):
       print('Q',txt[i])
       print('A',txt[i+1])

Text file contain question and answer, i try to make the output like:

question 
answer
question 
answer

like as it is in text file.

3 Answers

You can use a for-loop with a step:

for i in range(0,len(txt),2):
    print('Q',txt[i])
    print('A',txt[i+1])

you should use step inside range function.
something like this

for i in range(0,count+1, 2):
      print('Q',txt[i])
      print('A',txt[i+1])

range(startFrom, endWith, step)

Another way: store the question and answer data in different list and then use range.

txt = '''what's you'r name?
my name is Micheal
how old are you?
I'm 33 year's old'''

data = txt.split('\n')
ques = data[0::2]
ans = data[1::2]
for i in range(len(ques)):
    print(f'Question:{ques[i]}')
    print(f'Answer:{ans[i]}')

>>> Question:what's you'r name?
    Answer:my name is Micheal
    Question:how old are you?
    Answer:I'm 33 year's old
Related