0% found this document useful (0 votes)
4 views3 pages

Message

The document defines a quiz application with classes for managing questions and quizzes, allowing users to add, delete, and answer questions. It includes functionality for reading from and writing to a JSON file containing questions. The interactive quiz class extends the base quiz functionality to provide a user interface for quiz management and execution.

Uploaded by

hoangkhhoi1805
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views3 pages

Message

The document defines a quiz application with classes for managing questions and quizzes, allowing users to add, delete, and answer questions. It includes functionality for reading from and writing to a JSON file containing questions. The interactive quiz class extends the base quiz functionality to provide a user interface for quiz management and execution.

Uploaded by

hoangkhhoi1805
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 3

import random

import json

class Question:
"""Encapsulates a question with its details."""

def __init__(self, question_text, answer_text, points):


self._question_text = question_text
self._answer_text = answer_text
self._points = points

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 check_answer(self, user_answer):


return user_answer.lower() == self._answer_text.lower()

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 __init__(self, file_path):


self.file_path = file_path
self._questions = self._read_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 add_question(self, question):


if isinstance(question, Question):
self._questions.append(question)
self._write_questions()
print("Question added successfully!")
else:
print("Error: Invalid question object.")

def delete_question(self, index):


if 0 <= index < len(self._questions):
removed_question = self._questions.pop(index)
self._write_questions()
print(f"Question '{removed_question.get_question_text()}' deleted
successfully!")
else:
print("Error: Invalid question index.")

def get_questions(self):
return self._questions

class InteractiveQuiz(Quiz):
"""Extends Quiz with interactive user interface."""

def __init__(self, file_path):


super().__init__(file_path)

def _get_valid_int_input(self, prompt):


while True:
try:
value = int(input(prompt))
return value
except ValueError:
print("Error: Please enter a valid number.")

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)

print("\nAnswer the following questions:")


for question in self._questions:
user_answer = input(question.get_question_text() + " ")
if question.check_answer(user_answer):
print("Correct!")
score += question.get_points()
else:
print(f"Wrong! The correct answer is
{question.get_answer_text()}.")

percentage = (score / total_points) * 100 if total_points > 0 else 0


print(f"\nYou scored {score}/{total_points} ({percentage:.2f}%).")
print("Congratulations! You passed!" if percentage > 50 else "Sorry, you
failed. Better luck next time!")

# Main execution
quiz = InteractiveQuiz(r"questions.json")
quiz.modify_quiz()
quiz.start_quiz()

You might also like