Creating a quiz game in Python can be an exciting project for beginners to hone their programming skills while having fun. We’ll build a simple quiz game that presents users with multiple-choice questions on various topics, keeps track of their scores, and displays the correct answers at the end of each quiz.
First, let’s outline the steps we’ll take to build the quiz game:
- Define a list of questions, each containing the question itself, options, and the correct answer.
- Implement functions to display questions, accept user input, and calculate scores.
- Create a loop to iterate through the questions, present them to the user, and update the score accordingly.
- Display the final score and correct answers at the end of the quiz.
Now, let’s dive into the code implementation:
# Define the list of questions
questions = [
{
"question": "What is the capital of France?",
"options": ["London", "Paris", "Berlin", "Rome"],
"correct_answer": "Paris"
},
{
"question": "What is the largest planet in our solar system?",
"options": ["Mars", "Venus", "Jupiter", "Saturn"],
"correct_answer": "Jupiter"
},
{
"question": "Who wrote 'To Kill a Mockingbird'?",
"options": ["Harper Lee", "J.K. Rowling", "Stephen King", "Ernest Hemingway"],
"correct_answer": "Harper Lee"
}
]
# Function to display questions and accept user input
def present_question(question):
print(question["question"])
for idx, option in enumerate(question["options"], 1):
print(f"{idx}. {option}")
user_input = input("Enter your answer (1-4): ")
return user_input
# Function to check the user's answer and update the score
def check_answer(question, user_answer):
if question["options"][int(user_answer) - 1] == question["correct_answer"]:
return True
return False
# Main function to run the quiz
def run_quiz(questions):
score = 0
for question in questions:
user_input = present_question(question)
if check_answer(question, user_input):
print("Correct!\n")
score += 1
else:
print("Incorrect!\n")
print(f"Quiz completed! Your score is: {score}/{len(questions)}\n")
print("Correct answers:")
for question in questions:
print(f"{question['question']}: {question['correct_answer']}")
# Run the quiz
if __name__ == "__main__":
run_quiz(questions)
In this code, we first define a list of questions as a list of dictionaries. Each dictionary contains the question itself, options for the answer, and the correct answer.
We then define three functions:
present_question
: This function takes a question dictionary as input, displays the question and options to the user, and accepts their input.check_answer
: This function takes a question dictionary and the user’s input, checks if the user’s answer is correct, and returns True or False accordingly.run_quiz
: This is the main function that runs the quiz. It iterates through the list of questions, presents each question to the user, checks their answer, updates the score, and finally displays the score and correct answers at the end.
By running the run_quiz
function, users can participate in the quiz, answer questions, and receive feedback on their performance.
This quiz game provides a basic framework that can be expanded upon by adding more questions, implementing a timer, or even incorporating a graphical user interface (GUI) for a more engaging user experience. Additionally, you can explore saving and loading quizzes from external files, allowing for customization and scalability.
How to test the code?
- Start the Quiz: Run the Python script in your local environment. You’ll see the quiz start with the first question displayed, prompting you to enter your answer.
- Answer the Question: Input the number corresponding to your answer choice and press Enter. You’ll receive immediate feedback on whether your answer was correct or incorrect.
- Proceed to the Next Question: After each answer, the quiz will automatically move on to the next question until all questions have been answered.
- Final Score: At the end of the quiz, your total score out of the total number of questions will be displayed along with the correct answers to each question.
Output:
What is the capital of France?
1. London
2. Paris
3. Berlin
4. Rome
Enter your answer (1-4): 2
Correct!
What is the largest planet in our solar system?
1. Mars
2. Venus
3. Jupiter
4. Saturn
Enter your answer (1-4): 3
Incorrect!
Who wrote 'To Kill a Mockingbird'?
1. Harper Lee
2. J.K. Rowling
3. Stephen King
4. Ernest Hemingway
Enter your answer (1-4): 1
Correct!
Quiz completed! Your score is: 2/3
Correct answers:
What is the capital of France?: Paris
What is the largest planet in our solar system?: Jupiter
Who wrote 'To Kill a Mockingbird'?: Harper Lee
By following these steps, you can effectively test the quiz game and observe its responses.