Mastering Python: Day 10 — 🧠Multiple-Choice Quiz Game in Python

Sumayyea Salahuddin
5 min readNov 1, 2023

--

Photo by Nguyen Dang Hoang Nhu on Unsplash

This article provides a detailed overview of Day 10 in a Python coding challenge. The Python script provided is an improved quiz game that allows users to test their knowledge by selecting from multiple-choice options. It achieves this by presenting a series of questions and providing feedback based on the user’s responses. Let us analyze the code:

# Day 10
# Multiple-Choice Quiz Game in Python

The comments at the beginning of the code indicate that it is part of a coding challenge (Day 10) and its objective is to implement an interactive, multiple-choice quiz game in Python where the user is asked a series of questions, given feedback on their responses, and congratulated as the quiz champion if they answer all questions correctly.

import random

The first line of code imports Python’s random module that generates random numbers and simplifies program randomization. It can generate random integers, floating-point numbers, sequence items, shuffling lists, creating random seeds for repeatability, and more, making it a versatile tool for Python programs that need randomness.

# Define a list of questions, options, and correct answers as a dictionary
quiz_data = [
{
"question": "Which planet is known as the Red Planet?",
"options": ["a) Venus", "b) Mercury", "c) Earth", "d) Mars"],
"correct_answer": "d"
},
{
"question": "Who developed the theory of relativity?",
"options": ["a) Isaac Newton", "b) Albert Einstein", "c) Galileo Galilei", "d) Marie Curie"],
"correct_answer": "b"
},
{
"question": "What is the largest ocean on Earth?",
"options": ["a) Pacific Ocean", "b) Indian Ocean", "c) Southern Ocean", "d) Atlantic Ocean"],
"correct_answer": "a"
},
{
"question": "What is the fastest land animal on Earth?",
"options": ["a) Cheetah", "b) Lion", "c) Elephant", "d) Giraffe"],
"correct_answer": "a"
},
{
"question": "Who is the author of the Harry Potter book series?",
"options": ["a) J.R.R. Tolkien", "b) C.S. Lewis", "c) J.K. Rowling", "d) George R.R. Martin"],
"correct_answer": "c"
}
]

The dictionary quiz_data consists of lists, each containing three key-value pairs: a question, a list of possible options, and its corresponding answer.

# Create a list of indices from 0 to the length of quiz_data - 1
indices = list(range(len(quiz_data)))

Next, a list of indices ranging from 0 to the length of quiz_data minus 1 is generated and stored in variable indices.

# Shuffle the indices to get a random order
random.shuffle(indices)

These indices are then shuffled to randomize the order of the questions.

# Initialize a variable to keep track of the score
score = 0

The variable score is initialized to keep track of the user’s score.

# Iterate through the questions and ask the user
for i in indices:
current_question = quiz_data[i]

print(f"Question: {current_question['question']}")
for option in current_question['options']:
print(option)

user_answer = input("Your answer (a/b/c/d): ").strip().lower()

# Check if the user's answer is correct
if user_answer == current_question['correct_answer']:
print("Correct!\n")
score += 1
else:
print(f"Wrong! The correct answer is: {current_question['correct_answer'].upper()}\n")

Next, the code iterates through the questions in the quiz_data dictionary and interacts with the user. Here is a breakdown of the various elements:

  1. The statement “for i in indices:” iterates through the list of indices, determining the randomized order of the questions. The script is designed to present each question to the user individually.
  2. The line “current_question = quiz_data[i]” retrieves the current question from the quiz_data dictionary by using the current index, i.
  3. The line “print(f”Question: {current_question[‘question’]}”)” displays the current question to the user.
  4. The “for option in the current_question[‘options’]:” is the loop function that is used to display every possible option for the current question.
  5. The user’s answer is obtained through the input function and prompting them to enter a choice (a/b/c/d). The strip() method is used to extract the answer entered by the user. The lower() method then converts the answer to lowercase and any leading or trailing whitespaces are removed.
  6. The statement “if user_answer == current_question[‘correct_answer’]:” is used to verify if the user’s answer matches the correct answer for the current question. If the user’s answer is correct, the script will inform them and increase the score variable. However, if the answer is incorrect, the script will display the correct answer to the user.
# Display the final score
print(f"You scored {score} out of {len(quiz_data)} questions.")

Once all the questions have been answered, the code will display the user’s final score by printing the number of correct answers out of the total number of questions.

if score == len(quiz_data):
print("Congratulations! You are the quiz champion!")

If the user answers all the questions correctly and their score is equal to the number of questions, the code will display a message saying “Congratulations!” You are the champion of the quiz!

To summarize, this code creates an engaging multiple-choice quiz experience for the user. It is designed to provide feedback based on the user’s responses and will congratulate them if they answer all the questions correctly.

Here is the complete code:

# Day 10
# Multiple-Choice Quiz Game in Python

import random

# Define a list of questions, options, and correct answers as a dictionary
quiz_data = [
{
"question": "Which planet is known as the Red Planet?",
"options": ["a) Venus", "b) Mercury", "c) Earth", "d) Mars"],
"correct_answer": "d"
},
{
"question": "Who developed the theory of relativity?",
"options": ["a) Isaac Newton", "b) Albert Einstein", "c) Galileo Galilei", "d) Marie Curie"],
"correct_answer": "b"
},
{
"question": "What is the largest ocean on Earth?",
"options": ["a) Pacific Ocean", "b) Indian Ocean", "c) Southern Ocean", "d) Atlantic Ocean"],
"correct_answer": "a"
},
{
"question": "What is the fastest land animal on Earth?",
"options": ["a) Cheetah", "b) Lion", "c) Elephant", "d) Giraffe"],
"correct_answer": "a"
},
{
"question": "Who is the author of the Harry Potter book series?",
"options": ["a) J.R.R. Tolkien", "b) C.S. Lewis", "c) J.K. Rowling", "d) George R.R. Martin"],
"correct_answer": "c"
}
]

# Create a list of indices from 0 to the length of quiz_data - 1
indices = list(range(len(quiz_data)))

# Shuffle the indices to get a random order
random.shuffle(indices)

# Initialize a variable to keep track of the score
score = 0

# Iterate through the questions and ask the user
for i in indices:
current_question = quiz_data[i]

print(f"Question: {current_question['question']}")
for option in current_question['options']:
print(option)

user_answer = input("Your answer (a/b/c/d): ").strip().lower()

# Check if the user's answer is correct
if user_answer == current_question['correct_answer']:
print("Correct!\n")
score += 1
else:
print(f"Wrong! The correct answer is: {current_question['correct_answer'].upper()}\n")

# Display the final score
print(f"You scored {score} out of {len(quiz_data)} questions.")

if score == len(quiz_data):
print("Congratulations! You are the quiz champion!")

The output of the code is:

Output — Day 10 Python Code

Please visit the following GitHub Repository containing each day’s code with outputs:

If you enjoyed the article and would like to show your support, please consider:

👏 Clap for the story (100 Claps) and follow me 👉🏻Sumayyea Salahuddin

📑 View more content on my Medium Profile

🔔 Follow Me: Medium | GitHub | TikTok

🚀 Help me in reaching to a wider audience by sharing my content with your friends and colleagues.

--

--