0% found this document useful (0 votes)
17 views24 pages

PSPP Assignment No.14

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

PSPP Assignment No.14

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

DEPARTMENT OF ELECTRONICS AND COMMUNICATION ENGINEERNING

GE3151- PROBLEM SLOVING AND PYTHON PROGRAMMING

TOPIC : GENERATE QUIZ APP USING PYTHON SCRIPT

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

S.No COs RBTL Marks (40)


1 CO105.1 K2
2 CO105.2 K2
3 CO105.3 K3
4 CO105.4 K3
5 CO105.5 K3
6 CO105.6 K3
Total Marks

FACULTY IAQC COORDINATER HOD PRINCIPAL


TABLE OF CONTENT

PAGE
SERIAL
CONTENT NUMBER
NUMBER

1 ABSTRACT 4

2 INTRODUCTION 5

3 PROJECT PLANNING 6

4 DESIGN THE SYSTEM 7

5 IMPLEMENTATION 9

6 TESTING THE EVALUATION 11

7 SAMPLE PROGRAM 13

8 SAMPLE OUTPUT 17

FUTURE ENHANCEMENTS FOT THE ONLINE


9 19
QUIZ APPLICATION

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 core functionality is built using Python, incorporating libraries such as


requests for API integration and html for handling special characters in the
retrieved data. The application dynamically generates quizzes, presents questions
and options to users, and validates their responses. Instant feedback is provided
for each question, allowing users to track their performance in real time.

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.

Future enhancements could include a graphical user interface (GUI), user


authentication for personalized experiences, and analytics to track performance
over time. Additionally, incorporating features such as timed quizzes or category-
specific challenges could further broaden the application's appeal.

This project demonstrates the power of combining Python programming with


API-based data integration to create a simple yet effective interactive system. The
Online Quiz Application highlights the potential of technology to enhance
learning and entertainment in a fast, reliable, and customizable manner.
CHAPTER-2

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.

This project focuses on creating a streamlined experience for users, allowing


them to specify the number of questions and difficulty levels before starting the
quiz. Questions are dynamically retrieved from the OpenTDB API and presented
to the user along with four randomized answer options. By implementing real-
time feedback, the system fosters active learning as users receive immediate
results for their selected answers.

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

4.Designing the System


The Online Quiz Application is designed with simplicity and functionality in mind, focusing
on providing a seamless user experience through dynamic question retrieval and intuitive
navigation. Below is a detailed breakdown of the system's design:

System Architecture

The system follows a modular architecture with clear separation of concerns:

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.

Flow of the Application

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.

User Interface Design

The application uses a command-line interface with:

 Clear prompts for user inputs.


 Numbered answer options for simplicity.
 Informative messages to guide the user through each step.
Key Considerations

 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.

5.1 Core Modules and 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.

5.2 Quiz Execution

a) Interactive User Interface (CLI)

 The quiz is implemented as a command-line interface (CLI) for simplicity.


 Users are prompted to:
1. Specify the number of questions they want.
2. Select the difficulty level (easy, medium, hard).
b) Real-Time Interaction

 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.

c) Score Tracking and Feedback

 After each answer, the system provides instant feedback:


o Displays "Correct!" if the answer is right.
o Shows the correct answer if the response is incorrect.
 A running score is maintained throughout the quiz.

5.3 Error Handling and Validation

 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.

5.4 Completion and Scoring

 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.Testing and Evaluation


The testing and evaluation phase ensures that the Online Quiz Application operates as intended,
meets user expectations, and handles edge cases effectively. The focus is on verifying
functionality, performance, and usability while identifying and fixing potential bugs.

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

Simulated real-world usage by testing different scenarios:

 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:

def __init__(self, question_text, options, correct_option):

"""

Initialize a question with its text, options, and the correct answer.

:param question_text: The question text as a string.

:param options: A list of options (strings).

:param correct_option: The index of the correct option (0-based).

"""

self.question_text = question_text

self.options = options

self.correct_option = correct_option

def is_correct(self, answer):

"""

Check if the given answer index is correct.

:param answer: The index of the selected answer (0-based).

:return: True if correct, False otherwise.

"""

return answer == self.correct_option

def fetch_questions(amount=5, category=None, difficulty=None):

"""

Fetch quiz questions from the Open Trivia Database.


:param amount: Number of questions to fetch.

:param category: Optional category ID for questions.

:param difficulty: Difficulty level ("easy", "medium", "hard").

:return: A list of Question objects.

"""

url = "https://opentdb.com/api.php"

params = {

"amount": amount,

"type": "multiple", # Fetch only multiple-choice questions

if category:

params["category"] = category

if difficulty:

params["difficulty"] = difficulty

response = requests.get(url, params=params)

data = response.json()

questions = []

if data["response_code"] == 0:

for item in data["results"]:

question_text = html.unescape(item["question"])

incorrect_answers = [html.unescape(ans) for ans in item["incorrect_answers"]]

correct_answer = html.unescape(item["correct_answer"])

options = incorrect_answers + [correct_answer]

correct_index = len(incorrect_answers) # The correct answer is always added last

options.sort() # Randomize options order

correct_index = options.index(correct_answer)

questions.append(Question(question_text, options, correct_index))


else:

print("Failed to fetch questions. Please try again.")

return questions

def run_quiz(questions):

"""

Run the quiz by displaying questions and collecting user responses.

:param questions: A list of Question objects.

"""

score = 0

print("Welcome to the Online Quiz App!\n")

for idx, question in enumerate(questions, start=1):

print(f"Question {idx}: {question.question_text}")

for i, option in enumerate(question.options):

print(f" {i + 1}. {option}")

while True:

try:

answer = int(input("Your answer (1-4): ")) - 1

if 0 <= answer < len(question.options):

break

else:

print("Invalid choice. Please select a number between 1 and 4.")

except ValueError:

print("Invalid input. Please enter a number.")

if question.is_correct(answer):

print("Correct!\n")

score += 1

else:
print(f"Wrong! The correct answer was: {question.options[question.correct_option]}\n")

print(f"Quiz completed! Your score: {score}/{len(questions)}")

if __name__ == "__main__":

num_questions = int(input("Enter the number of questions you want: "))

difficulty = input("Choose difficulty (easy, medium, hard or leave blank): ").strip().lower() or None

quiz_questions = fetch_questions(amount=num_questions, difficulty=difficulty)

if quiz_questions:

run_quiz(quiz_questions)

else:

print("No questions available. Please try again later.")


CHAPTER-8
8. sample output
CHAPTER-9

9.Future Enhancements for the Online Quiz Application

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:

9.1 Graphical User Interface (GUI)

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.

9.2 User Authentication and Profiles

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.

9.3 Gamification and Leaderboards


Incorporating gamification features such as leaderboards, achievements, and badges could
increase user engagement and competition. This feature can be extended with time-based
challenges or multiplayer modes.

 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.

9.5 Detailed Analytics and Progress Tracking

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.

9.6 Quiz Customization and Categories

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.

9.7 Multi-language Support

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.

9.9 Integration with Social Media

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.

9.10 AI-Powered Personalization

Incorporating Artificial Intelligence (AI) to provide personalized quizzes based on a user’s


strengths and weaknesses could revolutionize the quiz experience. By analyzing past
performance, AI could suggest specific questions or topics that need improvement.

 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.

Throughout its development, the application focuses on simplicity, ease of use,


and scalability. By using Python's powerful libraries like requests and html,
the application ensures seamless integration with the API and clean presentation
of question data. The interactive command-line interface is intuitive, allowing
users to select quiz parameters, answer questions, and view their performance in
real time.

The project successfully meets its objectives by allowing for customizable


quizzes, error handling, and a clear display of results. It also lays the foundation
for future enhancements such as a graphical user interface (GUI), user
authentication, gamification features like leaderboards, and analytics to track
performance.

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

You might also like