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

Interactive Quiz Management System

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)
12 views3 pages

Interactive Quiz Management System

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

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 = [Link](f)
return [Question(q["question"], q["answer"], q["points"]) for q in
data]
except (FileNotFoundError, [Link]):
return []

def _write_questions(self):
with open(self.file_path, "w", encoding="utf-8") as f:
[Link]([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):
[Link](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"[Link]")
quiz.modify_quiz()
quiz.start_quiz()

Common questions

Powered by AI

The 'InteractiveQuiz' class extends the functionality of the 'Quiz' class by adding an interactive user interface layer, which allows users to dynamically modify the quiz by adding or deleting questions through a command-line interface. Unique features include prompting the user for input to add or delete questions, validating input for numerical values, and providing a system to quiz users interactively, scoring and giving feedback based on responses .

The 'InteractiveQuiz' promotes active learning by enabling users to engage directly with the quiz content through dynamic interaction—adding and deleting questions and answering questions in a shuffled order. This method contrasts with static quizzes' fixed structure, fostering a more engaging and adaptable learning environment. Potential benefits include enhanced user interest and retention, improved critical thinking from diverse problem exposure, and greater user autonomy in learning, leading to deeper and more personalized education experiences .

The system's error handling in the 'Quiz' class, especially within file operations, involves managing exceptions like FileNotFoundError and json.JSONDecodeError to ensure continuity and robustness. This is done by defaulting to an empty question list when such errors occur. Potential improvements could include logging errors to provide developers insight into issues for faster debugging and implementing alerts to inform users of file access problems directly .

User input validation in the 'InteractiveQuiz' class is critical for preventing errors and ensuring smooth user interaction. It is implemented in methods like '_get_valid_int_input', which repeatedly prompts the user until a valid integer input is received, thus avoiding input-related crashes or logical errors. This validation ensures that user commands are correctly interpreted, which is essential for operations such as adding the appropriate number of points to questions or selecting the correct index for question deletion .

The 'modify_quiz' method facilitates user-driven modification by allowing users to add or delete questions interactively. It challenges typical static nature of quizzes by introducing flexibility, enabling real-time updates to the quiz content that reflect user preferences and needs. This method addresses challenges such as maintaining engagement by keeping quiz content current and relevant, and ensuring operational integrity when questions are dynamically modified .

Points allocation in the quiz system assigns different weights to questions, influencing the assessment value by emphasizing the significance of particular questions over others. This allows for differentiation among questions based on their complexity or importance, fundamentally affecting the strategic approach a user might take during a quiz, and impacting the user's final score and perceived challenge level .

The 'Question' class is responsible for encapsulating the details of a question, namely the question text, the correct answer, and the points associated with it. It provides methods to access these details (get_question_text, get_answer_text, get_points) and checks if a user's answer is correct through 'check_answer'. This class contributes to the overall system by serving as a fundamental building block for question handling and ensuring that each question can be reliably created, stored, and validated .

The 'InteractiveQuiz' class provides completion feedback by calculating and displaying the score and percentage of correct answers, then congratulating users if they pass or encouraging them to try again if they fail. This feedback mechanism has implications for learning as it reinforces achievements, motivates improvement, and provides a summary of performance, which are critical for learning reinforcement and progression .

The 'start_quiz' method uses randomization to shuffle the order of questions, impacting the quiz-taking experience by preventing memorization of question patterns and encouraging genuine engagement with each question. This randomization leads to a more challenging and fair assessment by ensuring that each quiz iteration is unique, reducing the predictability of question sequences .

The 'Quiz' class manages questions by reading them from a file at initialization and providing methods to add or delete questions. The '_read_questions' method attempts to read questions from a JSON file, handling file not found and JSON decoding errors gracefully by returning an empty list. Data integrity during file operations is ensured by the '_write_questions' method, which consistently writes the state of the question list back to the file after modifications, using JSON serialization to preserve structure and content accuracy .

You might also like