|
import json |
|
import random |
|
|
|
class QCMTool: |
|
def __init__(self, json_file): |
|
""" |
|
Initialize the QCM tool with a JSON file containing questions. |
|
""" |
|
self.json_file = json_file |
|
self.questions = self.load_questions() |
|
|
|
def load_questions(self): |
|
""" |
|
Load questions from the JSON file. |
|
""" |
|
with open(self.json_file, 'r') as file: |
|
questions = json.load(file) |
|
return questions |
|
|
|
def pick_random_question(self): |
|
""" |
|
Pick a random question from the loaded questions. |
|
""" |
|
return random.choice(self.questions) |
|
|
|
def check_answer(self, question, user_answer): |
|
""" |
|
Check if the user's answer is correct and provide an explanation. |
|
""" |
|
if user_answer == question["correct_answer"]: |
|
return True, question["explanation"] |
|
else: |
|
return False, question["explanation"] |
|
|
|
def run(self): |
|
""" |
|
Run the QCM tool: pick a question, ask the user, and check the answer. |
|
""" |
|
question = self.pick_random_question() |
|
print("Question:", question["question"]) |
|
for i, option in enumerate(question["options"], 1): |
|
print(f"{chr(64 + i)}. {option}") |
|
|
|
user_answer = input("Your answer (enter the option letter, e.g., A, B, C, D): ").strip().upper() |
|
try: |
|
|
|
option_index = ord(user_answer) - 65 |
|
if 0 <= option_index < len(question["options"]): |
|
selected_option = question["options"][option_index] |
|
is_correct, explanation = self.check_answer(question, selected_option) |
|
if is_correct: |
|
print("Correct! 🎉") |
|
else: |
|
print("Incorrect! 😞") |
|
print("Explanation:", explanation) |
|
else: |
|
print("Invalid option letter. Please try again.") |
|
except (ValueError, IndexError): |
|
print("Invalid input. Please enter a valid option letter (A, B, C, D).") |
|
|
|
|
|
qcm_tool = QCMTool('info/questions.json') |
|
|
|
|
|
qcm_tool.run() |