🎓 A1Learner
🔍
0 of 52 lessons completed

Python Project: A Quiz Game

A quiz game asks questions, checks each answer, and prints a final score. Each question is a dict with the question text, the choices, and the right answer.

One question as a dict

The dict holds the question, the choices, and the right answer. Each part has its own key.

q = {"question": "What is 2 + 2?", "choices": ["3", "4", "5"], "answer": "4"}
print(q["question"])
print(q["choices"])
print("Right answer:", q["answer"])

Check one answer

One if compares the given answer with the right one. The printout says Right or Wrong.

q = {"question": "What is 2 + 2?", "choices": ["3", "4", "5"], "answer": "4"}
given = "4"
if given == q["answer"]:
    print("Right!")
else:
    print("Wrong!")

Score across questions

The loop checks each answer in turn. The score grows by 1 for each right answer.

questions = [
    {"question": "What is 2 + 2?", "answer": "4"},
    {"question": "What is the capital of France?", "answer": "Paris"},
]
given = ["4", "London"]
score = 0
for i in range(len(questions)):
    if given[i] == questions[i]["answer"]:
        score = score + 1
print("Score:", score, "out of", len(questions))

Example

questions = [
    {"question": "What is 2 + 2?", "choices": ["3", "4", "5"], "answer": "4"},
    {"question": "What is the capital of France?", "choices": ["London", "Paris", "Rome"], "answer": "Paris"},
    {"question": "Which planet is known as the Red Planet?", "choices": ["Venus", "Mars", "Jupiter"], "answer": "Mars"},
]
given = ["4", "Paris", "Jupiter"]
score = 0
for i in range(len(questions)):
    q = questions[i]
    print("Q:", q["question"])
    print("Choices:", q["choices"])
    print("Given:", given[i])
    if given[i] == q["answer"]:
        print("Right!")
        score = score + 1
    else:
        print("Wrong! The answer is", q["answer"])
print("Final score:", score, "out of", len(questions))

Key points

  • Quiz: a set of questions with a score for right answers
  • Use a list of dicts to hold the questions
  • Give each dict three keys: question, choices, and answer
  • Use a loop to ask each question in turn
  • Add 1 to the score for each right answer
  • Print the final score after the loop, as one line

In this example, the questions list holds three dicts, and given holds three scripted answers. The loop takes one question at a time. It prints the question, the choices, and the given answer. A right answer prints Right and adds 1 to the score. A wrong answer prints the right one instead. The last line prints the final score: 2 out of 3.

Note

The answers here are fixed in the code, so every run gives the same score.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Python Playground

Exercise

How does the game store its questions?