PSPP Assignment No.14
PSPP Assignment No.14
SUBMITTED BY,
812024106051-VIGNESHWARAN .S
812024106052-VINODHINI.K
812024106053-YUVARAJ.C
ANNA UNIVERSITY
CHENNAI
DECEMBER-2024
Marks Split up
Rubrics RBTL Marks Marks
Allotted (40)
obtained
Comprehension K2
of the project
Project K3
Execution
Degree of K3
result accuracy
Presentation K3
Project Report K3
compliance
Collaboration K3
and Teamwork
Total Marks
PAGE
SERIAL
CONTENT NUMBER
NUMBER
1 ABSTRACT 4
2 INTRODUCTION 5
3 PROJECT PLANNING 6
5 IMPLEMENTATION 9
7 SAMPLE PROGRAM 13
8 SAMPLE OUTPUT 17
10 CONCLUSION 21
11 REFERENCES 22
CHAPTER-1
1.Abstract
The Online Quiz Application is a Python-based system designed to provide an
engaging and interactive way for users to test their knowledge across a variety of
topics. The application leverages the Open Trivia Database (OpenTDB) API to
fetch multiple-choice questions in real time, offering users a dynamic and diverse
quiz experience. Users can customize the quiz by specifying the number of
questions and selecting a preferred difficulty level, making the application
versatile for educational or entertainment purposes.
The system features an intuitive command-line interface where users interact with
the quiz seamlessly. Questions are randomized, and correct answers are validated
based on indices, ensuring an engaging user experience. A scoring mechanism is
implemented to display the user’s final score at the end of the quiz, enhancing the
competitive and educational value of the application.
2.Introduction
The Online Quiz Application is an interactive system developed using Python,
aimed at providing users with an engaging way to test their knowledge and learn
new information. Designed to leverage the Open Trivia Database (OpenTDB)
API, the application dynamically fetches multiple-choice questions, ensuring a
fresh and diverse quiz experience with every session. The use of Python as the
programming language emphasizes simplicity, efficiency, and scalability,
making the application suitable for a wide range of audiences and purposes.
A significant feature of the application is its ability to handle input validation and
provide meaningful error messages, ensuring a smooth user experience. Python’s
requests library is used to fetch data from the API, and the html library helps
decode special characters, ensuring the display of clean and user-friendly
question text. The system also includes a scoring mechanism, which tallies the
number of correct responses and provides a performance summary at the end of
the quiz.
The application serves as a foundation for creating more advanced quiz systems,
with future possibilities including graphical interfaces, timed quizzes, user
authentication for personalized experiences, and detailed analytics. By
demonstrating the integration of external APIs with Python programming, this
project showcases how modern technology can create interactive and educational
tools. This introduction to quiz-based learning systems highlights their potential
to make education and entertainment accessible, dynamic, and enjoyable
CHAPTER-3
3.Project Planning
The Online Quiz Application is designed to be a lightweight, interactive system that
dynamically fetches and presents multiple-choice questions from the Open Trivia Database
(OpenTDB) API. To ensure the successful execution and scalability of the project, detailed
planning has been undertaken.
Objectives
1. Dynamic Question Retrieval: Integrate the OpenTDB API to fetch a fresh set of
multiple-choice questions each time a quiz is initiated.
2. Customizable User Experience: Allow users to select the number of questions and
difficulty levels for personalized quizzes.
3. Real-Time Feedback: Implement a scoring system that provides immediate feedback
on user responses.
4. User-Friendly Interface: Design an intuitive command-line interface that ensures
smooth interaction.
5. Scalable Foundation: Build a modular and extensible codebase to accommodate future
enhancements, such as graphical interfaces and advanced analytics.
Development Phases
1. Requirement Analysis:
o Define the features needed, such as API integration, dynamic question loading,
and scoring.
o Gather feedback on potential enhancements, including timed quizzes and
leaderboards.
2. System Design:
o Develop a logical flow for the quiz, from user input to fetching questions and
displaying results.
o Use modular programming to separate concerns (e.g., question fetching, answer
validation, score calculation).
3. Implementation:
o Use Python to write core functionality, leveraging the requests library for
API calls and html for text formatting.
o Develop robust error handling to manage API failures and invalid user inputs.
4. Testing and Debugging:
o Test the application with different parameters (question count, difficulty levels).
o Validate edge cases, such as incomplete data from the API or incorrect user
inputs.
5. Deployment and Feedback:
o Deploy the application for real-world use and gather feedback for refinement.
CHAPTER-4
System Architecture
1. Question Fetching Module: Interacts with the Open Trivia Database (OpenTDB) API
to retrieve multiple-choice questions.
2. Quiz Logic Module: Handles question presentation, user input validation, and score
calculation.
3. Feedback and Results Module: Provides real-time feedback for each question and
displays the final score summary.
1. Initialization:
o The application begins by asking the user to specify the number of questions
and difficulty level.
o This input is used to configure the API request parameters.
2. Fetching Questions:
o The system sends a request to the OpenTDB API, retrieves the questions, and
decodes any HTML-encoded characters.
o Questions and answers are randomized to ensure a fair and engaging quiz
experience.
3. Quiz Execution:
o Each question is displayed one at a time, along with four answer options.
o The user selects their answer, which is validated against the correct answer
index.
4. Scoring and Feedback:
o For every correct response, the score is incremented, and the user is notified of
their success.
o If the response is incorrect, the correct answer is displayed for immediate
learning.
5. Result Display:
o At the end of the quiz, the total score and performance summary are shown.
Error Handling: Ensures robust handling of invalid inputs and API failures, providing
meaningful error messages.
Extensibility: Modular design allows future enhancements, such as adding graphical
interfaces or integrating a leaderboard.
This system design ensures an efficient, engaging, and user-friendly quiz experience while
laying a foundation for scalability and future enhancements.
CHAPTER-5
5.Implementation
The implementation of the Online Quiz Application focuses on integrating the Open Trivia
Database (OpenTDB) API with a Python-based system to provide a dynamic, user-friendly
quiz experience. Below is a detailed explanation of the code’s implementation, covering key
components and their functionalities.
a) Question Class
A custom Question class is implemented to encapsulate the quiz question, available options,
and the correct answer index.
It includes a method is_correct(answer) to validate the user's input against the correct
option.
b) Fetch Questions
The fetch_questions function sends an HTTP request to the OpenTDB API using the
requests library.
Parameters such as amount (number of questions) and difficulty are dynamically set
based on user input.
The API response, containing questions and answers, is processed:
o The correct answer is appended to the list of incorrect answers.
o Options are randomized, ensuring fairness.
o Special HTML characters in the questions and options are decoded using the
html.unescape function.
Each question is displayed with four answer options, numbered for easy selection.
Users input their choice, which is validated to ensure it is within the acceptable range.
Ensures that:
o API failures are gracefully handled with an appropriate error message.
o User inputs are validated to prevent invalid selections (e.g., non-numeric or out-of-
range answers).
The system provides informative prompts and error messages to guide users.
At the end of the quiz, the total score and number of correct answers are displayed to the
user.
5.5.Future Enhancements
Graphical Interface: Transitioning from CLI to a graphical interface using frameworks like
Tkinter or Flask.
Leaderboards: Adding user authentication to track scores and implement leaderboards for
competition.
Timed Questions: Introducing a timer for each question to increase difficulty and
engagement.
This implementation ensures that the quiz is functional, reliable, and provides an engaging user
experience. The modular structure of the code also supports future scalability and
enhancements.
CHAPTER-6
6.1 Testing
1. Unit Testing
Each function and component was tested independently to confirm their correctness.
Question Class:
o Verified the creation of Question objects with appropriate attributes
(question_text, options, correct_option).
o Tested the is_correct() method for various inputs to ensure correct validation of
answers.
fetch_questions() Function:
o Tested API integration to verify that questions are retrieved successfully for various
configurations (e.g., difficulty levels, number of questions).
o Checked edge cases such as invalid API responses or network failures.
Input Handling:
o Ensured proper validation for numeric inputs in answer selection and error messages
for invalid inputs.
2. Integration Testing
Ensured that the system works as a whole when different components interact.
Verified the seamless flow from fetching questions to presenting them to the user and
tracking scores.
Tested the handling of randomized options to ensure the correct answer is still validated after
shuffling.
3. Functional Testing
Normal Case: Quiz with valid user inputs and complete interaction.
Boundary Case: Inputting the lowest (1) and highest (4) options during the quiz.
Invalid Case: Entering non-numeric or out-of-range values.
4. Performance Testing
Load Testing: Tested the system with a maximum of 50 questions fetched from the API in one
session.
Response Time: Measured the delay in fetching and displaying questions to ensure minimal
lag.
6.2 Evaluation
1. Success Criteria
Accuracy: Correct answers were validated accurately, and incorrect responses displayed
appropriate feedback.
Reliability: The system consistently handled valid and invalid inputs without crashing.
Usability: Users reported that the interface was intuitive and the flow of the quiz was smooth.
2. Identified Issues
API Limitations: Occasionally, the API returned fewer questions than requested due to a
limited question pool for specific difficulties or categories.
Input Validation: Some users attempted to input non-numeric characters, requiring enhanced
error messages.
3. Improvements Made
Added a check to handle API responses with fewer questions than requested, displaying a
meaningful message to the user.
Enhanced error handling for non-numeric and invalid inputs during answer selection.
CHAPTER-7
7.Sample program
import requests
import html
class Question:
"""
Initialize a question with its text, options, and the correct answer.
"""
self.question_text = question_text
self.options = options
self.correct_option = correct_option
"""
"""
"""
"""
url = "https://opentdb.com/api.php"
params = {
"amount": amount,
if category:
params["category"] = category
if difficulty:
params["difficulty"] = difficulty
data = response.json()
questions = []
if data["response_code"] == 0:
question_text = html.unescape(item["question"])
correct_answer = html.unescape(item["correct_answer"])
correct_index = options.index(correct_answer)
return questions
def run_quiz(questions):
"""
"""
score = 0
while True:
try:
break
else:
except ValueError:
if question.is_correct(answer):
print("Correct!\n")
score += 1
else:
print(f"Wrong! The correct answer was: {question.options[question.correct_option]}\n")
if __name__ == "__main__":
difficulty = input("Choose difficulty (easy, medium, hard or leave blank): ").strip().lower() or None
if quiz_questions:
run_quiz(quiz_questions)
else:
While the current implementation of the Online Quiz Application is functional and provides a
dynamic and interactive quiz experience, there are several areas where enhancements can be
made to improve its features, user engagement, and scalability. Below are some potential future
enhancements for the system:
Currently, the application uses a command-line interface (CLI), which is suitable for simple
interactions. However, implementing a Graphical User Interface (GUI) using frameworks
like Tkinter (for desktop applications) or Flask (for web applications) could significantly
enhance user experience.
Benefits:
o More intuitive and visually appealing.
o Interactive buttons, dropdowns, and media (images/videos) can be incorporated
for a richer experience.
o Improved accessibility for users unfamiliar with command-line tools.
Adding a user authentication system would allow users to log in, track their scores, and manage
their quiz history. A profile system could store user-specific data such as quiz preferences, past
performance, and personalized settings.
Benefits:
o Personalized quiz experience based on user history and preferences.
o Ability to save progress in long quizzes or store results for future analysis.
o Secure login, enabling users to access their data on different devices.
Benefits:
o Increases user motivation by adding a competitive element.
o Encourages repeated interaction with the app.
o Allows users to challenge others and track their progress compared to peers.
9.4 Timed Quizzes and Question Difficulty
Introducing a timer for each question could increase the challenge level and allow users to
compete against time, further enhancing the quiz's engagement factor.
Benefits:
o Adds a sense of urgency and excitement to the quiz experience.
o Allows users to select timed or untimed quiz options, providing flexibility.
Implementing analytics features would allow users to see detailed insights into their quiz
performance. This could include trends over time, question difficulty analysis, and areas where
the user needs improvement.
Benefits:
o Personalized feedback to help users improve their knowledge.
o Visualizations such as graphs or heat maps to show progress over time.
o Can be integrated with a backend database to store and analyze data efficiently.
Allowing users to choose from various categories (e.g., History, Science, Sports) or customize
the quiz by selecting their own topics could broaden the application's appeal.
Benefits:
o Increases user engagement by offering quizzes tailored to specific interests.
o Provides flexibility and variety in the quiz content.
o Can integrate with additional APIs that support topic-based or subject-specific
questions.
Supporting multiple languages could open the application to a wider audience. The question
pool from the OpenTDB API could be extended to other languages, and the user interface could
be localized.
Benefits:
o Expands the user base to non-English speaking regions.
o Improves accessibility and inclusivity for global audiences.
9.8 Mobile Application
Creating a mobile version of the quiz application using frameworks like React Native or
Flutter would allow users to engage with the quizzes on their smartphones or tablets.
Benefits:
o Increased accessibility and convenience for users to take quizzes on-the-go.
o Push notifications for reminders and updates.
o Enhances user engagement with mobile-optimized design.
Adding the ability to share quiz results or challenge friends on social media platforms like
Facebook, Twitter, or Instagram could increase the app's visibility and user engagement.
Benefits:
o Boosts the app’s exposure by allowing users to share their results.
o Promotes social interaction, increasing retention rates.
Benefits:
o Delivers a more tailored and effective learning experience.
o Improves user retention by offering quizzes that match their knowledge level.
o Predicts the user’s preferred difficulty level and topics.
CHAPTER-10
10.Conclusion
The Online Quiz Application developed using Python and the Open Trivia
Database (OpenTDB) API demonstrates a successful integration of external data
sources with an interactive user experience. This project provides a dynamic and
engaging quiz platform where users can test their knowledge across various
categories and difficulty levels. The system effectively retrieves real-time
questions, randomizes answer options, and offers immediate feedback, making it
both an educational and entertaining tool.
Overall, the Online Quiz Application proves the potential of combining Python
programming with external APIs to create an engaging, flexible, and scalable
learning tool. By continuing to iterate and enhance the application, it can evolve
into a robust platform that meets the needs of a wide range of users, from students
and educators to casual learners and quiz enthusiasts.
CHAPTER-11
11. References
1. Open Trivia Database (OpenTDB) API
o OpenTDB API documentation for fetching quiz questions and categories.
o URL: https://opentdb.com/
2. Python Requests Library
o Python’s requests library for handling HTTP requests to the Open Trivia
Database API.
o Documentation: https://docs.python-requests.org/en/master/
3. Python HTML Library
o Python’s html module used for decoding HTML entities in question and answer
text.
o Documentation: https://docs.python.org/3/library/html.html
4. Python Programming Language
o Python language documentation, as it provides the core structure for the quiz
application.
o Official Python website: https://www.python.org/
5. Python Documentation
o General Python documentation for functions and libraries used in the code,
including handling lists, loops, and basic data structures.
o URL: https://docs.python.org/3/
6. Stack Overflow
o For troubleshooting and code snippets, especially regarding API handling, user
input validation, and debugging.
o URL: https://stackoverflow.com/
7. GeeksforGeeks
o For understanding Python concepts, including the use of libraries and functions
in building interactive applications.
o URL: https://www.geeksforgeeks.org/python-programming-language/
8. Real Python
o Python tutorials and guides for best practices, especially when handling APIs
and creating interactive applications.
o URL: https://realpython.com/
These references include documentation, resources, and learning platforms that were helpful
in guiding the development of the Online Quiz Application. If further details or additional
resources are needed, these references can be explored for deeper understanding and technical
insights