Python MCQs Quiz

It is not very difficult to write a script in Python to interact with MCQs and test user performace through interactive quiz. The program needs to display a number of questions, then wait for user to answer each question, and finally calculate and present the score to him on the screen.

Here is an example: we will create a class which has the following functions:

  • Read question from a file : It will read a json file containing MCQs and answers in the form of "key : value" pairs, and return them in the form of a dictionary, that will be available to the class instance (object).

  • Display MCQs : Display each MCQ and get the answer, compare it to a stored value and add 1 to score or nil if comparison return False.

  • Display result at the end after going through all questions and give comment or advice to user on his result.

Example of JSON File

Here is an example of a json file with only two questions. You can add as many as you want. It takes the form of a dictionary with questions as keys and the right answers as values. The questions is multi-line multiple choice questions, with each line separated by a linefeed "\n".

{
"A String object must have :\n 1- Double Quotes\n 2- Single Quotes\n 3- Triple quotes\n 4- All of the above\n": "4'",
"A list is a sequence of :\n 1- Integers\n 2- Strings\n 3- Any object\n 4- None of the above\n": "3"
}

Here is a Script Example:

class Quiz():
    def __init__(self, score = 0):
        "initialize the score value"
        self.score = score

    def Read_mcqas(self):
        "read the json file containing MCQs and answers in key:value pairs and return a dictionary"
        import json
        global mcas
        with open("MCQs.json", 'r') as f:
            mcas = json.load(f)
            return mcas
    def Display_MCQs(self):
        "Display each MCQ and get answer, compare to value and add to score"
        mcqs = self.Read_mcqas()
        for mcq in mcqs:
            print(mcq)
            ans = input("Select number of correct answer: ")
            if ans == mcqs[mcq]:
                self.score += 1
        self.Result()
    def Result(self):
        "display result and advice"
        print("Here is the total score ...:", self.score)
        print("This is a percentage of ...", (self.score/len(mcas))*100, "%")

m = Quiz() 
print(m.Display_MCQs())