This quiz game does two jobs at once: it tests what you know about Python, and its code shows you how to build any quiz you like. Every question is a dictionary (question, choices, answer, explanation) inside a list, and the order is shuffled each time.
Get a question wrong and the game explains the right answer, so you learn as you play.
Play Python Quiz
Press ▶ Play to start the game. When it asks you something, type your answer and press Enter.
View and edit the code (47 lines)
How to play
- Answer each question with a, b, c or d.
- You get an explanation after every answer.
- Your score and a rating appear at the end.
The complete Python Quiz code
Here is the whole program (47 lines). It only uses Python's standard library, so it runs anywhere Python 3 is installed.
import random
QUESTIONS = [
{"q": "What does print(2 ** 3) show?", "choices": ["6", "8", "9", "23"], "answer": "b",
"why": "** means 'to the power of', so 2 ** 3 is 2 x 2 x 2 = 8."},
{"q": "Which of these makes a list?", "choices": ["(1, 2)", "{1, 2}", "[1, 2]", "<1, 2>"], "answer": "c",
"why": "Square brackets make a list. Round brackets make a tuple, curly ones a set."},
{"q": "What type does input() always give you?", "choices": ["int", "str", "float", "bool"], "answer": "b",
"why": "input() returns text (str). Use int() to turn it into a number."},
{"q": "What is len('hello')?", "choices": ["4", "5", "6", "'o'"], "answer": "b",
"why": "len() counts the characters: h-e-l-l-o is 5."},
{"q": "Which keyword leaves a loop early?", "choices": ["stop", "exit", "break", "return"], "answer": "c",
"why": "break ends the loop straight away. continue skips to the next round."},
{"q": "What does range(3) produce?", "choices": ["1, 2, 3", "0, 1, 2", "0, 1, 2, 3", "3, 2, 1"], "answer": "b",
"why": "range(3) starts at 0 and stops before 3."},
{"q": "What is 7 // 2?", "choices": ["3.5", "3", "4", "1"], "answer": "b",
"why": "// divides and drops the fraction, so 7 // 2 is 3. 7 % 2 would be the remainder, 1."},
{"q": "How do you start a function?", "choices": ["function f():", "def f():", "func f():", "f() =>"], "answer": "b",
"why": "Python functions start with def, then the name, brackets and a colon."},
]
random.shuffle(QUESTIONS)
score = 0
print("PYTHON QUIZ - answer with a, b, c or d")
for number, item in enumerate(QUESTIONS, 1):
print(f"\nQ{number}. {item['q']}")
for letter, choice in zip("abcd", item["choices"]):
print(f" {letter}) {choice}")
reply = input("Your answer: ").strip().lower()
while reply not in ("a", "b", "c", "d"):
reply = input("Type a, b, c or d: ").strip().lower()
if reply == item["answer"]:
score += 1
print("Correct!", item["why"])
else:
right = item["choices"]["abcd".index(item["answer"])]
print(f"Not quite. The answer is {item['answer']}) {right}. {item['why']}")
total = len(QUESTIONS)
print(f"\nYou scored {score}/{total} ({score * 100 // total}%).")
if score == total:
print("Perfect! You know your Python.")
elif score >= total // 2:
print("Good work! Review the ones you missed and try again.")
else:
print("Keep going! Every game on this site will help.")How the Python Quiz game works, step by step
01Store each question as a dictionary
A dictionary keeps the question, the four choices, the right letter and an explanation together. The whole quiz is a list of these, so adding a question is adding one item.
{"q": "What is len('hello')?", "choices": ["4", "5", "6", "'o'"], "answer": "b", "why": "..."}02Shuffle the order
random.shuffle() mixes the list in place, so each game asks the questions in a different order.
random.shuffle(QUESTIONS)03Number questions with enumerate
enumerate(QUESTIONS, 1) counts from 1, and zip("abcd", choices) pairs letters with answers for printing.
for number, item in enumerate(QUESTIONS, 1):
for letter, choice in zip("abcd", item["choices"]):
print(f" {letter}) {choice}")04Score and explain
A right answer adds a point. A wrong one looks up the right choice by turning the letter back into a position with "abcd".index().
right = item["choices"]["abcd".index(item["answer"])]What you'll learn
- A list of dictionaries as data
random.shuffle()enumerate()andzip()- Percentages with
// - Input validation loops
Python concepts in this game:
Python Quiz coding challenges
Write the key parts of the game yourself. Press Run to try your code and Check to test it. Each challenge you pass earns a star (saved in this browser).
Mark an answer
Write is_right(question, reply): return True if reply (any case, spaces allowed) matches the question's "answer".
Hint
reply.strip().lower() == question["answer"]
Show a solution
def is_right(question, reply):
return reply.strip().lower() == question["answer"]
q = {"q": "2 + 2?", "choices": ["3", "4"], "answer": "b"}
print(is_right(q, " B "))Print a question
Write show(question) that prints the question, then each choice on its own line as a) text, b) text and so on.
Hint
for letter, choice in zip("abcd", question["choices"]):
Show a solution
def show(question):
print(question["q"])
for letter, choice in zip("abcd", question["choices"]):
print(f"{letter}) {choice}")
show({"q": "Best snake?", "choices": ["python", "cobra", "boa"], "answer": "a"})Run a mini quiz
Ask both questions in QUIZ with input(), count the right answers, and finish by printing exactly Score: 1/2 (with the real score).
Hint
Loop for item in QUIZ:, read input(item["q"]), and add 1 when it equals item["a"].
Show a solution
QUIZ = [{"q": "2 + 2 = ?", "a": "4"},
{"q": "Capital of France?", "a": "paris"}]
score = 0
for item in QUIZ:
reply = input(item["q"] + " ").strip().lower()
if reply == item["a"]:
score += 1
print(f"Score: {score}/{len(QUIZ)}")Make it your own
Once your challenges pass, try one of these upgrades:
- Load questions from a CSV or JSON file.
- Add a timer for each question.
- Shuffle the answer choices too (and track where the right one moved).
- Save high scores with names.
Frequently asked questions
How do you make a quiz game in Python?
Put each question in a dictionary with its choices and answer, keep them in a list, loop through the list asking with input(), and add a point for each right reply.
How do I shuffle quiz questions?
Call random.shuffle(questions) before the loop. It mixes the list in place.
Can I use this quiz for my class?
Yes. Replace the QUESTIONS list with your own questions. The rest of the program works with any number of questions.