Python Forum
help setting questions and answers in quiz game?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
help setting questions and answers in quiz game?
#4
(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

Reply


Messages In This Thread
RE: help setting questions and answers in quiz game? - by buran - May-10-2018, 07:35 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  quiz game - problem with loading statements from file lapiduch 2 1,105 Apr-20-2023, 06:13 PM
Last Post: deanhystad
Question Why do these codes give different answers? pooyan89 5 2,542 Dec-15-2020, 06:54 PM
Last Post: DeaD_EyE
  Basic Quiz/Game searching1 10 5,772 Nov-18-2018, 03:58 AM
Last Post: ichabod801
  Two Questions Regarding My Trivia Game martin28 1 2,415 Aug-19-2018, 02:07 PM
Last Post: martin28
  Quiz Game Help (ASAP Please!) beginnercoder04 2 3,228 Apr-15-2018, 04:13 AM
Last Post: beginnercoder04
  Just some second choice answers help please ajaY 6 5,157 Apr-07-2017, 08:25 PM
Last Post: micseydel

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020