Message
Message
import json
class Question:
"""Encapsulates a question with its details."""
def get_question_text(self):
return self._question_text
def get_answer_text(self):
return self._answer_text
def get_points(self):
return self._points
def __str__(self):
return f"{self._question_text} (Points: {self._points})"
def to_dict(self):
return {"question": self._question_text, "answer": self._answer_text,
"points": self._points}
class Quiz:
"""Manages a collection of questions."""
def _read_questions(self):
try:
with open(self.file_path, encoding="utf-8") as f:
data = json.load(f)
return [Question(q["question"], q["answer"], q["points"]) for q in
data]
except (FileNotFoundError, json.JSONDecodeError):
return []
def _write_questions(self):
with open(self.file_path, "w", encoding="utf-8") as f:
json.dump([q.to_dict() for q in self._questions], f, indent=4)
def get_questions(self):
return self._questions
class InteractiveQuiz(Quiz):
"""Extends Quiz with interactive user interface."""
def _add_questions(self):
while True:
q_text = input("Enter the question: ")
a_text = input("Enter the answer: ")
points = self._get_valid_int_input("Enter the points for this question:
")
new_question = Question(q_text, a_text, points)
self.add_question(new_question)
if input("Add another question? (yes/no): ").strip().lower() != "yes":
break
def _delete_questions(self):
while True:
if not self._questions:
print("No questions available to delete.")
break
for idx, q in enumerate(self._questions):
print(f"{idx + 1}. {q}")
index = self._get_valid_int_input("Enter the number of the question to
delete (0 to cancel): ")
if index == 0:
break
if 1 <= index <= len(self._questions):
self.delete_question(index - 1)
else:
print("Error: Invalid question number.")
if input("Delete another question? (yes/no): ").strip().lower() !=
"yes":
break
def modify_quiz(self):
choice = input("Do you want to modify the quiz? (add/delete/none):
").strip().lower()
if choice == "add":
self._add_questions()
elif choice == "delete":
self._delete_questions()
def start_quiz(self):
random.shuffle(self._questions)
score = 0
total_points = sum(q.get_points() for q in self._questions)
# Main execution
quiz = InteractiveQuiz(r"questions.json")
quiz.modify_quiz()
quiz.start_quiz()