Head office, Rana Pratap Bagh, Delhi011 2721 1512+91 97116 99511

Free detailed project guide

Build a science quiz game in Python

Write a complete quiz program with Python: a list of questions, a score, shuffling, a fact after each answer, a timer and a saved best score. No extra parts needed, only a computer and free software.

  • Class 9–12
  • Computer and coding
  • Medium
  • 3 to 4 hours
  • Free
  • Working model

What you will show: A program is a set of exact instructions: data in lists and dictionaries, decisions with if, repetition with loops and reusable functions. Cost: Python is free software from python.org (or may already be on the school or home computer). You need access to a computer; nothing has to be bought.

The science idea

Every app and game you use is a program: a list of exact instructions that a computer follows one after another. To write a program you must break a problem into small steps, which is called computational thinking. A quiz game is a perfect first project, because it needs all the basic ideas of programming in a small space: it stores data (the questions), repeats things (it asks several questions), makes decisions (is the answer right?), and remembers things (the score, and even a best score saved in a file).

The project uses Python, one of the most popular programming languages in the world, which is also used in science, artificial intelligence and web sites. Python is known for being easy to read. The ideas you will use are: variables (a name that holds a value, like score = 0), data types (numbers, text, and truth values), lists (an ordered collection, such as the four options), dictionaries (a collection of named items, such as a question with its options and answer), if and else (decisions), for and while (loops), and functions (named blocks of code that you can use again and again).

Before you write code it helps to draw a flowchart. A flowchart uses shapes: rounded boxes for the start and the end, rectangles for actions and diamonds for decisions. Following the arrows shows the order of the steps, including the loops. If you can draw a flowchart for the quiz, you understand the logic, and writing the code is just writing each box in Python. Indentation, the spaces at the start of a line, is very important in Python: it shows which lines belong inside a loop, an if or a function.

Real programs must cope with unexpected input. A player might type the letter x, or nothing at all, when you expected a number. Your program must not crash, so it checks the input and asks again, a technique called validation. Real programs also remember things between runs. Here the best score is saved in a small text file, and read back the next time the game starts. Reading a file that does not exist yet causes an error, so the program catches the error with try and except and uses a default instead.

Working like a software engineer also means testing. You will write a test plan, run the program with normal and with strange input, and fix what goes wrong. Reading error messages is a skill: Python tells you the line and the kind of error, such as a missing colon or a wrong indent. The finished program has about 100 lines. Understanding every line, and being able to change it, is the aim of this project.

Materials and tools

Cost: Free

Python is free software from python.org (or may already be on the school or home computer). You need access to a computer; nothing has to be bought.

Materials
What you needHow manyFree substitute or where to find it
A computer or laptop (Windows, macOS or Linux) with Python 3 installed1The school computer lab, a library computer or a home computer. Python 3 is free from python.org (an adult or teacher can help install it). Python 3.8 or newer is fine.
A text editor: IDLE (comes with Python) or any plain-text editor1IDLE is installed with Python. Notepad also works if you save the file with the extension .py.
Pencil, paper and ruler for the flowchart1 sheetFrom the notebook.
Your science textbook, to write extra questions1To check the facts. Use at least 10 questions.
A friend or family member to test the quiz1 or 2They try the game and tell you what is unclear.

Tools

  • Python 3 and its editor (IDLE)
  • A folder for the project, named quiz
  • Pen and paper for the flowchart
  • A phone or a notebook for the test plan

Safety first

Read this before you start

  • Download Python only from the official site, python.org, and with the help of an adult or teacher. Do not download programs from unknown sites or run code that you do not understand.
  • Take a short break every 30 to 40 minutes. Sit with a straight back, and look away from the screen from time to time.
  • Do not put your full name, address, phone number or school in a program that you share online. Use a nickname.
  • Save your file often, and keep a copy of the working version before you try something new.
  • The program only reads and writes one small file in its own folder. Do not change it to delete or change other files.

Parts and layout

These drawings show the parts and how they fit together. Keep them beside you while you build.

Scroll sideways to see the whole diagram.

Quiz program: the parts of quiz.pyThe program file quiz.py drawn as four stacked blocks. Block one: two imports, random and time. Block two: the data, a list called questions, where each question is a dictionary with a question, a list of options, the number of the right answer and a fact. Block three: four functions, load_best, save_best, ask_question and play. Block four: the main program, which says hello and repeats the game while the player wants to play.1Importsimport random (to shuffle the questions)import time (to time the player)2Data: the questions listquestions = [ {...}, {...}, ... ]one dictionary for each question(10 questions in the finished game)3Functionsload_best() reads the best score from a filesave_best(score) writes it to the fileask_question(item, number) asks one questionplay(name) plays one complete game4Main programsay hello and ask the name, thenrepeat play() until the player says noOne question (a dictionary){ "q": "Which planet is the Red Planet?", "options": ["Venus", "Mars", "Jupiter", "Mercury"], "answer": 2, "fact": "Mars looks red ..."}answer is the NUMBER of the rightoption, counting from 1 (here: Mars)
Figure 1. The parts of the programImports, data, functions and the main program, with one question dictionary shown in detail.

Scroll sideways to see the whole diagram.

Quiz program: what the player seesA text window showing the running quiz. It prints a welcome and asks for a name, then prints Question 1 with four options numbered 1 to 4 and asks for an answer. After the player types 2 the program prints Correct and a fact about Mars.quiz.pyWelcome to the Science Quiz!What is your name? AshaQuestion 1 : Which planet is known as the Red Planet? 1 ) Venus 2 ) Mars 3 ) Jupiter 4 ) MercuryYour answer (1-4): 2Correct!Fact: Mars looks red because its soil contains iron oxide.Question 2 : Which gas do plants take in from the air ...The program prints a question, then waits for the player to type an answer.
Figure 3. What the player seesThe quiz runs in a text window: it prints questions, waits for the player to type and then prints a reply and a fact.

Step-by-step build

13 steps. Do them in order, and test each part before you go on to the next.

  1. Install and test Python

    Ask an adult to install Python 3 from python.org if it is not already on the computer. On Windows, tick “Add Python to PATH” in the installer. Open IDLE, and type the line below, and press Enter. If it prints a message, Python works.

    print("Hello, Python!")

    Tip: The IDLE window with the three arrows >>> is called the shell. Use File, New File to open an editor window for your program.

  2. Plan with a flowchart

    On paper, draw the flowchart of the game: Start, ask the name, shuffle the questions, for each question show it, get a valid answer, check it, show a fact, then show the score and ask to play again. Compare it with the flowchart diagram on this page.

    Common mistake: Starting to type code before planning. If you do not know the steps in order, the code gets confused too.

  3. Create the file and say hello

    In IDLE choose File, New File and save it as quiz.py in your quiz folder. Type the lines below and run them with F5 (Run, Run Module). It should ask your name and say hello.

    print("Welcome to the Science Quiz!")
    player = input("What is your name? ").strip() or "Player"
    print("Hello,", player)

    Tip: input() always gives you text. The .strip() removes spaces at the ends, and “or Player” uses a default name if the player just presses Enter.

  4. Store the questions

    Make a list of questions. Each question is a dictionary with the question text, a list of four options, the number of the right option (counting from 1) and a fact. Type two questions first and add more later.

    questions = [
        {"q": "Which planet is known as the Red Planet?",
         "options": ["Venus", "Mars", "Jupiter", "Mercury"],
         "answer": 2,
         "fact": "Mars looks red because its soil contains iron oxide."},
        {"q": "What is the SI unit of force?",
         "options": ["Joule", "Pascal", "Newton", "Watt"],
         "answer": 3,
         "fact": "One newton gives a mass of 1 kg an acceleration of 1 m/s per second."},
    ]

    Common mistake: Forgetting a comma between two dictionaries or between two lines of one dictionary. A missing comma is the most common error in a list of data.

  5. Write the function that asks a question

    A function groups lines of code under a name. This one prints a question and its options, then loops until the player types 1, 2, 3 or 4, and returns True if the answer is right. Keep the lines inside the function indented by four spaces.

    def ask_question(item, number):
        print()
        print("Question", number, ":", item["q"])
        for i, option in enumerate(item["options"], start=1):
            print("  ", i, ")", option)
        while True:
            choice = input("Your answer (1-4): ").strip()
            if choice in ("1", "2", "3", "4"):
                return int(choice) == item["answer"]
            print("Please type 1, 2, 3 or 4.")

    Tip: enumerate(list, start=1) gives each item together with a counter that starts from 1, so the options are numbered the way people count.

  6. Write the game loop

    Write a loop that goes through the questions one by one. It adds 1 to the score if the answer is right, and shows the right answer if not. Put the lines below after the function. Run it and play.

    import random
    random.shuffle(questions)
    score = 0
    for number, item in enumerate(questions, start=1):
        if ask_question(item, number):
            print("Correct!")
            score += 1
        else:
            right = item["options"][item["answer"] - 1]
            print("Not quite. The answer is:", right)
        print("Fact:", item["fact"])
    print(player + ", you scored", score, "out of", len(questions))

    Common mistake: Writing = when you mean ==. A single = stores a value in a variable. A double == compares two values.

  7. Fix errors by reading them

    If Python prints an error, read the last line and the line number. SyntaxError means a missing bracket, quote or colon. IndentationError means the spaces are wrong. NameError means a name was misspelt. Fix one error at a time and run again.

    Tip: Python reports where it noticed the problem, which is sometimes one line after the real mistake. Check the line before it too.

  8. Add a message for the result

    Replace the last line with a result using if, elif and else. It calculates a percentage and prints one of three messages.

    percent = score * 100 / len(questions)
    if percent == 100:
        print("Perfect score!")
    elif percent >= 60:
        print("Well done!")
    else:
        print("Keep practising.")

    Tip: Python tests the conditions from top to bottom and runs only the first one that is true.

  9. Save and load the best score

    Add two functions that read and write a file called best_score.txt. The try and except block stops the program from crashing the first time, when the file does not exist.

    def load_best():
        try:
            with open("best_score.txt") as f:
                return int(f.read().strip())
        except (FileNotFoundError, ValueError):
            return 0
    
    
    def save_best(score):
        with open("best_score.txt", "w") as f:
            f.write(str(score))

    Common mistake: Writing the file without converting the number to text. f.write() needs a string, so use str(score).

  10. Time the player and put the game in a function

    Put the game loop in a function play(name) that also records the time with time.time() at the start and at the end. Then wrap it in a while loop that asks “Play again?”. The complete program is given in the last step.

    Tip: Test each new piece before you add the next. If something breaks, you know it is the last thing you added.

  11. Write a test plan and test

    Fill in the test table: try a right answer, a wrong one, the letter x, an empty entry, the number 5, all right, all wrong, and playing twice. Write what you expected and what happened.

    Common mistake: Testing only the answers that work. Real users type unexpected things, so test them too.

  12. Add your own questions

    Add at least 10 questions of your own from your textbook. Check each fact. Make sure that the answer number matches the position of the right option, counting from 1.

    Tip: A good quiz has options that look possible. Avoid silly wrong options.

  13. The complete program

    This is the whole program with 10 questions. Read each part and compare it with your own. Then change it: add questions, change the grading, or add a hint.

    # Science Quiz Game: a small program with questions, scoring and a best score.
    import random
    import time
    
    questions = [
        {"q": "Which planet is known as the Red Planet?",
         "options": ["Venus", "Mars", "Jupiter", "Mercury"], "answer": 2,
         "fact": "Mars looks red because its soil contains a lot of iron oxide, which is rust."},
        {"q": "Which gas do plants take in from the air to make food?",
         "options": ["Oxygen", "Carbon dioxide", "Nitrogen", "Hydrogen"], "answer": 2,
         "fact": "In photosynthesis plants use carbon dioxide, water and light to make glucose and oxygen."},
        {"q": "What is the chemical formula of water?",
         "options": ["H2O", "CO2", "O2", "NaCl"], "answer": 1,
         "fact": "A molecule of water has two hydrogen atoms and one oxygen atom."},
        {"q": "Which force pulls objects towards the Earth?",
         "options": ["Friction", "Gravity", "Magnetism", "Tension"], "answer": 2,
         "fact": "Gravity gives every object weight. Weight = mass x g."},
        {"q": "What is the SI unit of electric current?",
         "options": ["Volt", "Ohm", "Ampere", "Watt"], "answer": 3,
         "fact": "One ampere is one coulomb of charge passing a point every second."},
        {"q": "Which organ pumps blood around the body?",
         "options": ["Lungs", "Heart", "Liver", "Kidney"], "answer": 2,
         "fact": "The human heart beats about 70 times a minute at rest."},
        {"q": "At sea level, at what temperature does water boil?",
         "options": ["50 degrees C", "100 degrees C", "0 degrees C", "150 degrees C"], "answer": 2,
         "fact": "Water boils at a lower temperature on a mountain because the air pressure is lower."},
        {"q": "Which metal is a liquid at room temperature?",
         "options": ["Iron", "Mercury", "Copper", "Zinc"], "answer": 2,
         "fact": "Mercury is a liquid metal, but its vapour is poisonous, so we avoid it."},
        {"q": "About how long does sunlight take to reach the Earth?",
         "options": ["8 seconds", "8 minutes", "8 hours", "8 days"], "answer": 2,
         "fact": "Light travels about 300,000 km every second, so it takes about 8 minutes."},
        {"q": "What is the SI unit of force?",
         "options": ["Joule", "Pascal", "Newton", "Watt"], "answer": 3,
         "fact": "One newton is the force that gives a mass of 1 kg an acceleration of 1 m/s per second."},
    ]
    
    
    def load_best():
        try:
            with open("best_score.txt") as f:
                return int(f.read().strip())
        except (FileNotFoundError, ValueError):
            return 0
    
    
    def save_best(score):
        with open("best_score.txt", "w") as f:
            f.write(str(score))
    
    
    def ask_question(item, number):
        print()
        print("Question", number, ":", item["q"])
        for i, option in enumerate(item["options"], start=1):
            print("  ", i, ")", option)
        while True:
            choice = input("Your answer (1-4): ").strip()
            if choice in ("1", "2", "3", "4"):
                return int(choice) == item["answer"]
            print("Please type 1, 2, 3 or 4.")
    
    
    def play(name):
        random.shuffle(questions)
        score = 0
        start = time.time()
        for number, item in enumerate(questions, start=1):
            if ask_question(item, number):
                print("Correct!")
                score += 1
            else:
                right = item["options"][item["answer"] - 1]
                print("Not quite. The answer is:", right)
            print("Fact:", item["fact"])
        seconds = round(time.time() - start)
        percent = score * 100 / len(questions)
        print()
        print(name + ", you scored", score, "out of", len(questions), "in", seconds, "seconds.")
        if percent == 100:
            print("Perfect score!")
        elif percent >= 60:
            print("Well done!")
        else:
            print("Keep practising.")
        best = load_best()
        if score > best:
            save_best(score)
            print("New best score!")
        else:
            print("Best score so far:", best)
    
    
    print("Welcome to the Science Quiz!")
    player = input("What is your name? ").strip() or "Player"
    while True:
        play(player)
        again = input("Play again? (y/n): ").strip().lower()
        if again != "y":
            break
    print("Thanks for playing,", player + "!")

    Tip: Put comments (lines starting with #) in your own version to explain each part in your own words. They are very useful in your report.

How it should look when it is finished

A file called quiz.py of about 100 lines that runs in a text window. It greets the player by name, asks ten science questions in a random order with four numbered options each, tells the player if each answer is right and shows a fact, then prints the score, the time taken and a message, and remembers the best score in a small file between games.

This is a description, not a photograph. Compare your own model with it and with the figures above.

How it works

When the program starts, Python runs the lines at the left margin from top to bottom: it imports two modules, defines the questions and the functions (which only store the instructions), and then reaches the main program, which asks the name and starts a loop.

The function play() shuffles the list of questions, then runs a for loop over them. For each question, ask_question() prints the text and the numbered options and keeps asking until the player types a valid number. It returns True or False, and the loop adds to the score or shows the right answer, then prints the fact. The program uses len(questions) so that you can add or remove questions without changing the code.

At the end, it works out the percentage and picks a message using if, elif and else. It reads the best score from the file with load_best(), compares, and if the new score is higher it writes it with save_best(). The outer while loop asks whether to play again and stops if the player does not type y.

Scroll sideways to see the whole diagram.

Quiz program: flowchartA flowchart of the quiz program. Start. Ask the name. Shuffle the questions and set the score to zero. For each question: show it, ask for an answer, check that the answer is 1 to 4 (if not, ask again), check if it is correct (add one to the score or show the right answer), show the fact. When there are no more questions: show the score, the time and a message, save the score if it is the best so far, and ask whether to play again. If yes, start again from the shuffle; if no, the program ends.StartAsk the player’s nameShuffle the questions;score = 0Show the questionand the optionsAnswer is1, 2, 3 or 4?Right answer?score = score + 1say CorrectSay Not quite andshow the right oneShow the factMorequestions?YesNo: ask againYesNoYesNoShow score, timeand a messageIf it is a new best,save it to the filePlay again?EndNoYesYes: go back to “Shuffle the questions” and play again
Figure 2. Flowchart of the quizRounded boxes start and end, rectangles are actions and diamonds are decisions. Arrows show the order and the loops.

Troubleshooting

If something goes wrong
What you seeLikely causeWhat to do
SyntaxError: invalid syntaxA missing colon, quote, bracket or comma.Look at the line named in the message and the one before it. Check that every ( has a ), every quote is closed and every if, for, def and while line ends with a colon.
IndentationErrorThe spaces at the start of lines are not consistent.Use four spaces for each level and do not mix tabs and spaces. Lines inside a function or loop must be indented the same.
NameError: name ‘scor’ is not definedA variable name is misspelt or used before it is created.Check the spelling, and make sure the variable is given a value before it is used.
The program says the right answer is wrongThe answer number in the data does not match the position of the right option, or input is compared as text.Count the options from 1 and make sure the answer matches. Compare int(choice) with the number.
The window closes at once when I double-click the fileThe program ended and the window closed.Run the file from IDLE (F5) or from a command window, so the output stays on the screen.
“python” is not recognisedPython is not on the PATH.Reinstall Python and tick “Add Python to PATH”, or run the file from IDLE.

Test and record

Run the program for each test. Write what you expect to happen before you try it, and what really happened. Mark pass or fail. Fix the program and test again if it fails.

Table: test plan and results
TestWhat I didWhat I expectedWhat happenedPass or fail
1. Right answerTyped the right numberCorrect! and score +1
2. Wrong answerTyped a wrong numberNot quite, right answer shown
3. Letter instead of numberTyped xAsks again, no crash
4. Empty inputPressed Enter onlyAsks again, no crash
5. Number out of rangeTyped 5Asks again, no crash
6. All answers rightAnswered every question rightPerfect score! and new best
7. Play againTyped y, then nPlays again, then ends

Copy the table into your notebook and write each reading as you take it, in pencil, with the date. Repeat every test at least three times and use the average. Then draw a graph or chart of your results.

Viva questions and answers

A teacher or a judge will ask you how your project works. Practise these eight questions and answer them in your own words.

  1. What is a variable?

    A name that refers to a value stored in the computer’s memory, such as score = 0. The value can change as the program runs.

  2. What is the difference between a list and a dictionary?

    A list is an ordered collection accessed by position (item[0]); a dictionary stores values under names, called keys (item["q"]).

  3. What is the difference between = and ==?

    A single = assigns a value to a variable. A double == compares two values and gives True or False.

  4. What is a function and why use one?

    A named block of code that can be used again. It avoids repetition, makes the program easier to read and to fix, and can take inputs and return a result.

  5. Why does indentation matter in Python?

    It shows which lines belong to a loop, an if or a function. Wrong indentation changes the meaning or causes an error.

  6. What is input validation and where did you use it?

    Checking that the user’s input is acceptable before using it. In ask_question() the loop keeps asking until the answer is 1, 2, 3 or 4.

  7. What does try and except do?

    It lets the program handle an error instead of crashing. If reading the best-score file fails, the program uses 0.

  8. What is a flowchart and what do the diamond and the rectangle mean?

    A diagram of the steps of a program. A rectangle is an action, a diamond is a decision with two exits (yes and no), and rounded boxes are the start and the end.

Free ebook: Viva Questions for Science Projects

Written report outline

Use these headings in your project file, and write each part in your own words. Add a title page, your diagrams, the precautions you took and the books or sites you used.

Aim
To design, write and test a quiz game in Python that uses lists, dictionaries, loops, decisions, functions and a file.
Apparatus
A computer with Python 3 and IDLE, a notebook, and a flowchart drawn on paper.
Procedure
Describe how you planned the flowchart, wrote the program step by step, tested each part, and fixed errors. Include the flowchart, the program with comments and the test table.
Observation
The test table of expected and actual results, and a screenshot of the program running.
Result
The finished program asks ... questions, handles wrong input without crashing, saves the best score, and passed all ... tests.
Conclusion
A program is built from small parts: data, decisions, loops and functions. Planning with a flowchart and testing with a plan make a program correct and reliable.

Free ebook: Writing a Science Project File

Take it further

  • Add a hint option: if the player types h, the program shows two wrong options removed.
  • Put the questions in a separate file (for example questions.txt) so that a teacher can add questions without editing the program.
  • Give a different score for easy and difficult questions and show the total points.
  • Add a timer for each question and take away points if the player is too slow.
  • Make a graphical version with the tkinter module that comes with Python.

Free ebooks, kits and help

Free ebooks for this project

Prefer to buy parts, or want help?

  • Ready-made projects and kits

    Matching ready-made projects, kits and spare parts are listed in the store under Robotics and Coding.

    Robotics and Coding
  • Stuck on a step?

    Send a message on WhatsApp and say which guide and which step you are on.

    Ask on WhatsApp
WhatsApp us