Python Quiz Application Project

Python project 14

Python Quiz Application Project

Create a reusable multiple-choice quiz that randomises question order, validates option numbers, explains every answer, calculates the final percentage, and keeps question content separate from the game logic.

Learn Python with mentor-guided projectsView all project ideas

What you will build

The application presents five Python questions in a new order each time. It accepts only a displayed option number, gives immediate feedback, and produces a score and percentage at the end.

Skills practised

  • Lists and dictionaries
  • Random shuffling
  • Functions and return values
  • Input validation and scoring

Requirements

  • Python 3.10 or later
  • A terminal or command prompt
  • No external packages
  • About 30 minutes to build

Full Python code

Save this code as quiz_application.py, then follow the run instructions below.

"""A reusable command-line multiple-choice quiz."""

from __future__ import annotations

import random


QUESTIONS = [
    {
        "question": "Which keyword defines a function in Python?",
        "options": ["func", "def", "function", "method"],
        "answer": 1,
        "explanation": "Python functions begin with the def keyword.",
    },
    {
        "question": "Which collection stores unique values?",
        "options": ["list", "tuple", "set", "string"],
        "answer": 2,
        "explanation": "A set keeps one instance of each hashable value.",
    },
    {
        "question": "What does len([10, 20, 30]) return?",
        "options": ["2", "3", "30", "60"],
        "answer": 1,
        "explanation": "The list contains three items.",
    },
    {
        "question": "Which block handles a raised exception?",
        "options": ["catch", "rescue", "except", "error"],
        "answer": 2,
        "explanation": "Python pairs try with one or more except blocks.",
    },
    {
        "question": "Which operator checks value equality?",
        "options": ["=", "==", "!=", ":="],
        "answer": 1,
        "explanation": "== compares values; = assigns a value.",
    },
]


def ask_question(item: dict[str, object], number: int) -> bool:
    options = item["options"]
    if not isinstance(options, list):
        raise TypeError("Question options must be a list.")

    print(f"\n{number}. {item['question']}")
    for index, option in enumerate(options, start=1):
        print(f"   {index}. {option}")

    while True:
        choice = input(f"Your answer [1-{len(options)}]: ").strip()
        if choice.isdigit() and 1 <= int(choice) <= len(options):
            break
        print("Choose one of the displayed option numbers.")

    correct = int(choice) - 1 == item["answer"]
    print("Correct!" if correct else f"Not quite. Correct answer: {options[item['answer']]}")
    print(item["explanation"])
    return correct


def run_quiz(questions: list[dict[str, object]]) -> int:
    shuffled = questions.copy()
    random.shuffle(shuffled)
    score = sum(ask_question(item, number) for number, item in enumerate(shuffled, start=1))
    percentage = score / len(shuffled) * 100 if shuffled else 0
    print(f"\nFinal score: {score}/{len(shuffled)} ({percentage:.0f}%)")
    return score


def main() -> None:
    print("Python Basics Quiz")
    run_quiz(QUESTIONS)


if __name__ == "__main__":
    main()

How the project works

Each question is a dictionary containing prompt text, options, the zero-based correct-answer index, and an explanation. This data-driven structure makes it easy to add questions without rewriting the quiz engine.

ask_question() returns a Boolean value, and Python treats True as one when sum() calculates the score. run_quiz() copies the list before shuffling so the original question bank remains unchanged.

Run the project

  1. Run python quiz_application.py.
  2. Read each question and its numbered options.
  3. Enter one of the displayed numbers.
  4. Review the explanation and final percentage.

Accuracy and safety notes

  • Answer index: list positions start at zero even though options display from one.
  • Data separation: question content is independent of input and scoring logic.
  • Empty lists: the percentage calculation safely handles an empty question bank.

Ways to extend it

Load questions from JSON, add categories and difficulty levels, limit response time, save high scores, or create a browser version with Flask.

Continue learning Python

Build the next project, return to the Softenant project library, or explore the Python programming course in Vizag for structured lessons, mentor feedback, and portfolio practice.