GITHUB REPO | FOLLOW ME ON -> TWITTER | LINKEDIN
Python Quiz App “QuizWiz” — Test Your Knowledge with Fun!
Are you ready to put your Python knowledge to the test? In this article, we’ll explore a Python quiz app that allows you to answer questions from various categories and difficulty levels. By the end of this article, you’ll have a better understanding of how to create interactive quiz applications using Python.
Experience the thrill of playing the game — click the play button below and play now!
The first thing we need to do is set up our Python QuizWiz. Open up your preferred code editor, create a new file, and save it with a descriptive name such as “quizwiz.py.
”. Also, create other files which will be used as modules and classquestion_data.py, question_model.py, quiz_process.py
question_data.py
I fetched questions from https://opentdb.com/api_config.php, where you can choose the number of questions, category, difficulty. Then it will generate an url where the questions will be in the Json format.
The code will look like this.
question_data = [
{
"category": "computers",
"difficulty": "easy",
"question": "Linus Torvalds created Linux and Git.",
"correct_answer": "True"
},
{
"category": "computers",
"difficulty": "easy",
"question": "Pointers were not used in the original C programming language; they were added later on in C++.",
"correct_answer": "False"
},
.....................
.....................
.....................
.....................
{
"category": "geography",
"difficulty": "medium",
"question": "Japan has left-hand side traffic.",
"correct_answer": "True"
},
{
"category": "geography",
"difficulty": "medium",
"question": "Liechtenstein does not have an airport.",
"correct_answer": "True"
}
]
category_list = list({question["category"] for question in question_data})
difficulty_list = list({question["difficulty"] for question in question_data})
category_list
and difficulty_list
iterates over each question in question_data
, retrieves the value of the category
and difficulty
key, and adds it to a set. Finally, the set is converted to a list. These lists will contain unique categories and difficulty levels extracted from the question_data
dataset.
question_model.py
class Question:
def __init__(self, q_text, q_answer):
self.text = q_text
self.answer = q_answer
The Question
class is a blueprint for creating question objects. Each question object has two attributes: text
and answer
.
The __init__
method is a special method that gets called when a new question object is created. It takes two parameters: q_text
and q_answer
. Inside the method, the text
attribute is assigned the value of q_text
, and the answer
attribute is assigned the value of q_answer
.
This class lets you build question objects capable of storing the content and response to a question. It gives an organized approach to handling the questions in your program.
quiz_process.py
The QuizProcessing
class handles the processing of a quiz. It keeps track of the question number, score, and the list of questions and answers. It provides methods to interact with the quiz, such as displaying questions, checking answers, and printing the user's answers along with the correct answers.
class QuizProcessing:
def __init__(self, ques_list)
def questions_remaining(self)
def next_question(self)
def check_answer(self, answer, q_answer)
def print_answers(self)
The __init__
method initializes the QuizProcessing
object by setting the initial values for the question number, score, question list, and answers list.
def __init__(self, ques_list):
self.question_number = 0
self.score = 0
self.question_list = ques_list
self.answers_list = []
The questions_remaining
method checks if there are any questions remaining in the quiz.
def questions_remaining(self):
return self.question_number < len(self.question_list)
The next_question
method displays the next question, prompts the user for an answer, and checks if the answer is correct. It updates the score and answers list accordingly.
def next_question(self):
ques = self.question_list[self.question_number]
self.question_number += 1
ans = input(f"Q.{self.question_number}: {ques.text} (True/False) - ")
self.answers_list.append(ans)
self.check_answer(ans, ques.answer)
The check_answer
method compares the user's answer with the correct answer and updates the score based on the correctness of the answer.
def check_answer(self, answer, q_answer):
if answer.lower() == q_answer.lower():
print("Your answer is correct.")
self.score += 1
else:
print("Your answer is wrong.")
print(f"Correct answer is: {q_answer}")
print(
f"Your current score is: {self.score}/{self.question_number}\n")
The print_answers
method prints the user's answers along with the correct answers for all the questions in the quiz, as well as the final score.
def print_answers(self):
print("You've completed the quiz.")
for i in range(len(self.question_list)):
question = self.question_list[i]
print(f"""For Q{i+1}.
Your answer was - {self.answers_list[i]}
Correct answer was - {question.answer}""")
print()
print(f"Your final score is: {self.score}/{self.question_number}")
print("Thank you for taking the quiz chellange.")
Using the QuizProcessing
class, you can create a quiz object, interact with the quiz by displaying questions, providing answers, and getting the final score and answers summary.
class QuizProcessing:
def __init__(self, ques_list):
self.question_number = 0
self.score = 0
self.question_list = ques_list
self.answers_list = []
def questions_remaining(self):
return self.question_number < len(self.question_list)
def next_question(self):
ques = self.question_list[self.question_number]
self.question_number += 1
ans = input(f"Q.{self.question_number}: {ques.text} (True/False) - ")
self.answers_list.append(ans)
self.check_answer(ans, ques.answer)
def check_answer(self, answer, q_answer):
if answer.lower() == q_answer.lower():
print("Your answer is correct.")
self.score += 1
else:
print("Your answer is wrong.")
print(f"Correct answer is: {q_answer}")
print(
f"Your current score is: {self.score}/{self.question_number}\n")
def print_answers(self):
print("You've completed the quiz.")
for i in range(len(self.question_list)):
question = self.question_list[i]
print(f"""For Q{i+1}.
Your answer was - {self.answers_list[i]}
Correct answer was - {question.answer}""")
print()
print(f"Your final score is: {self.score}/{self.question_number}")
print("Thank you for taking the quiz chellange.")
main.py
The main.py
file is responsible for executing the quiz program. It imports the necessary modules and interacts with the user to determine the category and difficulty level of the questions they want to answer.
from question_model import Question
from quiz_process import QuizProcessing
from question_data import question_data, category_list, difficulty_list
print("Categories Are - ")
for category in category_list:
print(category.capitalize(), end="\n")
category_choice = input(
"What category questions you like to answer? - ").lower()
print("\n")
print("Difficulties Are - ")
for difficulty in difficulty_list:
print(difficulty.capitalize(), end="\n")
difficulty_choice = input(
"What difficult level questions do you like to answer? - ").lower()
The program then creates a list of question objects based on the user’s choices and the available question data. If a valid question bank is created, a QuizProcessing
object is instantiated with the question bank.
question_bank = []
for question in question_data:
if category_choice in question["category"] and difficulty_choice in question["difficulty"]:
question_text = question["question"]
question_answer = question["correct_answer"]
new_question = Question(question_text, question_answer)
question_bank.append(new_question)
The program then proceeds to present each question to the user, prompt for answers, and provide feedback on correctness.
Finally, once all questions are answered, the program prints the user’s answers along with the correct answers and displays the final score. If an invalid choice is made in selecting the category or difficulty, an appropriate error message is displayed.
if question_bank:
quiz = QuizProcessing(question_bank)
print(f"Category: {category_choice.capitalize()}")
print(f"Difficulty: {difficulty_choice.capitalize()}")
while quiz.questions_remaining():
quiz.next_question()
quiz.print_answers()
else:
print("Wrong Choice. Try Again!!")
By running this file, the user can take a quiz by selecting the desired category and difficulty level of questions.
from question_model import Question
from quiz_process import QuizProcessing
from question_data import question_data, category_list, difficulty_list
print("Categories Are - ")
for category in category_list:
print(category.capitalize(), end="\n")
category_choice = input(
"What category questions you like to answer? - ").lower()
print("\n")
print("Difficulties Are - ")
for difficulty in difficulty_list:
print(difficulty.capitalize(), end="\n")
difficulty_choice = input(
"What difficult level questions do you like to answer? - ").lower()
question_bank = []
for question in question_data:
if category_choice in question["category"] and difficulty_choice in question["difficulty"]:
question_text = question["question"]
question_answer = question["correct_answer"]
new_question = Question(question_text, question_answer)
question_bank.append(new_question)
if question_bank:
quiz = QuizProcessing(question_bank)
# clear
print(f"Category: {category_choice.capitalize()}")
print(f"Difficulty: {difficulty_choice.capitalize()}")
while quiz.questions_remaining():
quiz.next_question()
quiz.print_answers()
else:
print("Wrong Choice. Try Again!!")
Sample Run
Features
Program’s Features
The program’s features include:
- User-friendly interface for selecting categories and difficulty levels.
- Dynamic question bank creation based on the user’s choices.
- Accurate tracking of correct and incorrect answers.
- Interactive quiz experience with question-and-answer display
Python Concepts and Techniques Used
The Python concepts and techniques used in the program include:
- Importing modules and classes to utilize existing code.
- Looping through data to display options and collect user input.
- Conditional statements to filter and select specific questions.
- Object-oriented programming to represent questions and process the quiz.
- Iteration through questions and collecting user answers.
We created a Python quiz app in this project that allows users to test their knowledge in several categories and difficulty levels. We went over the whole app development process, from picking categories and difficulty to presenting questions and delivering feedback. We learned about importing modules, dealing with data, and creating an interactive user experience using Python by constructing this quiz app.
Ready to Level Up? Complete These Challenges
Now that you’ve learned how to create a quiz app, it’s time to put your skills to the test! Here are some fun challenges to help you take your Python knowledge to the next level. Are you ready to level up? Let’s go!
- Add more categories and difficulty levels to the quiz.
- Implement a timer for each question to make the quiz more challenging.
- Include hints or explanations for incorrect answers.
- Expand the question bank by integrating an API to fetch new questions dynamically.
This article is a part of my Python Project Journal. To learn more about my journey in learning Python and to see my other projects, check out this project journal. Thank you!