May-10-2018, 07:35 AM
(May-10-2018, 02:55 AM)yoyoitsjess Wrote: I do have a question though, in your given code, on line 8, what does the i%2 do? I am trying to figure that out to myself but I can't come to a conclusion. Is it asking if each line is an even number?
%
is modulo operator. The result is the remainder of the division. So, yes, in this case i%2
checks for odd/even number. Remember indexing (thus also enumerate
) starts from 0. So if there is no reminder - it's a question (index is 0, 2, 4, etc.) and if there is reminder - it's answer (index is 1, 3, 5, etc.). Also remember that non-zero numbers are evaluated as True.using [the same] index is the most primitive/naive way to link question and answer. Not very pythonic though. Also note my use of enumerate, no need to use/increase index yourself.
more pythonic would be to zip the questions and answers list and get 2-element tuple:
class Quiz: def __init__(self, quiz_file): self.quiz_file = quiz_file self.questions = [] self.answers = [] with open(self.quiz_file, 'r') as f: for i, line in enumerate(f): if i%2: # this is answer self.answers.append(line.strip()) else: # this is question self.questions.append(line.strip()) def list_qa(self): for index, question, answer in enumerate(zip(self.questions, self.answers), start=1): print('Q{}: {}'.format(index, question)) print('A{}: {}'.format(index, answer)) print()I will stop here for now and leave to you to try figure for yourself how to get single question/answer pair from it.
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs