KAHIBARO Bookshelves
Discord Login Register

17.5. Quiz application

Planning Your Quiz Application

A quiz app is a great mini project because it combines:

  • User input and output
  • Conditions
  • Loops
  • Data collections
  • Basic program structure

In this chapter you will build a console-based quiz application that:

  • Asks multiple questions
  • Checks if the user’s answer is correct
  • Keeps track of the score
  • Shows the final result

You do not need any external libraries for this.

We’ll start with a simple version, then improve it step by step.


Designing the Quiz

Before writing code, plan what your quiz should do:

  1. Show a welcome message.
  2. Ask a question.
  3. Get the user’s answer.
  4. Check if the answer is correct.
  5. Update the score.
  6. Move to the next question.
  7. At the end, show the total score.

In words, this is basically:

$$
\text{repeat for each question: ask → answer → check → score}
$$

You’ll turn this into code using:

  • print() and input()
  • if statements
  • A loop (for is simplest here)
  • A data collection to store questions and answers

Step 1: A Single Question

Start with just one question to make sure the basic idea works.

print("Welcome to the quiz!")
score = 0
print("Question 1: What is the capital of France?")
answer = input("Your answer: ")
if answer == "Paris":
    print("Correct!")
    score = score + 1
else:
    print("Wrong. The correct answer is Paris.")
print("Your score is:", score)

This is not very flexible yet, but it proves the core logic works.


Step 2: Handling Case and Spaces

Users may type paris, PARIS, or add spaces. You can make the check more user-friendly by cleaning the input first.

Common tricks:

  • Remove extra spaces with .strip()
  • Make everything lowercase with .lower()
answer = input("Your answer: ")
# Clean up the answer
answer = answer.strip().lower()
if answer == "paris":
    print("Correct!")
    score = score + 1
else:
    print("Wrong. The correct answer is Paris.")

Now Paris, paris, PARIS are all accepted.


Step 3: Multiple Questions with a List

Instead of copying and pasting code for each question, store questions and answers in a list of dictionaries (or tuples). This makes your quiz easier to change.

Here is one way using dictionaries:

questions = [
    {
        "question": "What is the capital of France?",
        "answer": "paris"
    },
    {
        "question": "What is 5 + 7?",
        "answer": "12"
    },
    {
        "question": "What is the color of the sky on a clear day?",
        "answer": "blue"
    }
]

Then loop through this list:

print("Welcome to the quiz!")
score = 0
for q in questions:
    print()
    print(q["question"])
    user_answer = input("Your answer: ")
    user_answer = user_answer.strip().lower()
    if user_answer == q["answer"]:
        print("Correct!")
        score = score + 1
    else:
        print("Wrong. The correct answer is", q["answer"] + ".")
print()
print("You got", score, "out of", len(questions), "correct.")

You now have a complete basic quiz.


Step 4: Multiple-Choice Questions

Multiple-choice questions are easier for users and allow you to guide answers.

You can store:

  • The question text
  • A list of options
  • The correct option (for example, "a", "b", etc.)
questions = [
    {
        "question": "What is the capital of France?",
        "options": ["a) Berlin", "b) Madrid", "c) Paris", "d) Rome"],
        "answer": "c"
    },
    {
        "question": "Which number is even?",
        "options": ["a) 3", "b) 7", "c) 10", "d) 9"],
        "answer": "c"
    }
]

Loop with options:

print("Welcome to the multiple-choice quiz!")
score = 0
for q in questions:
    print()
    print(q["question"])
    for option in q["options"]:
        print(option)
    user_answer = input("Your answer (a, b, c, or d): ")
    user_answer = user_answer.strip().lower()
    if user_answer == q["answer"]:
        print("Correct!")
        score = score + 1
    else:
        print("Wrong. The correct answer was", q["answer"])
print()
print("You scored", score, "out of", len(questions))

Step 5: Adding Feedback and Percentages

A quiz feels nicer when it gives more than just the raw number.

You can calculate a percentage:

$$
\text{percentage} = \frac{\text{correct answers}}{\text{total questions}} \times 100
$$

And then give feedback based on that.

total_questions = len(questions)
percentage = (score / total_questions) * 100
print()
print("You scored", score, "out of", total_questions)
print("Percentage:", round(percentage, 2), "%")
if percentage == 100:
    print("Amazing! Perfect score!")
elif percentage >= 70:
    print("Well done!")
elif percentage >= 50:
    print("Not bad, but you can improve.")
else:
    print("Keep practicing!")

Step 6: Organizing Code with Functions

To make the quiz easier to read and extend, you can separate parts into functions:

  • A function to run the whole quiz
  • A function to ask a single question and return 1 or 0 for correct/incorrect
def ask_question(q):
    print()
    print(q["question"])
    for option in q["options"]:
        print(option)
    user_answer = input("Your answer (a, b, c, or d): ")
    user_answer = user_answer.strip().lower()
    if user_answer == q["answer"]:
        print("Correct!")
        return 1
    else:
        print("Wrong. The correct answer was", q["answer"])
        return 0
def run_quiz(questions):
    print("Welcome to the quiz!")
    score = 0
    for q in questions:
        score = score + ask_question(q)
    total_questions = len(questions)
    percentage = (score / total_questions) * 100
    print()
    print("You scored", score, "out of", total_questions)
    print("Percentage:", round(percentage, 2), "%")
# Define questions
questions = [
    {
        "question": "What is the capital of France?",
        "options": ["a) Berlin", "b) Madrid", "c) Paris", "d) Rome"],
        "answer": "c"
    },
    {
        "question": "Which number is even?",
        "options": ["a) 3", "b) 7", "c) 10", "d) 9"],
        "answer": "c"
    }
]
# Start the quiz
run_quiz(questions)

This structure makes it easier to:

  • Add more questions
  • Change how questions are asked
  • Reuse run_quiz with different question sets

Step 7: Simple Enhancements

Once your basic quiz works, you can add small features. Here are a few that stay within beginner-friendly Python.

1. Limiting Invalid Answers

For multiple choice, you may want to force the user to enter only a, b, c, or d.

def get_valid_answer():
    while True:
        user_answer = input("Your answer (a, b, c, or d): ")
        user_answer = user_answer.strip().lower()
        if user_answer in ["a", "b", "c", "d"]:
            return user_answer
        else:
            print("Please enter a, b, c, or d.")
def ask_question(q):
    print()
    print(q["question"])
    for option in q["options"]:
        print(option)
    user_answer = get_valid_answer()
    if user_answer == q["answer"]:
        print("Correct!")
        return 1
    else:
        print("Wrong. The correct answer was", q["answer"])
        return 0

2. Showing Correct Answer Text

Instead of just showing the letter, show the full option text.

One way: use the same letter positions:

  • a → index 0
  • b → index 1
  • c → index 2
  • d → index 3
def ask_question(q):
    print()
    print(q["question"])
    for option in q["options"]:
        print(option)
    letters = ["a", "b", "c", "d"]
    correct_index = letters.index(q["answer"])
    correct_text = q["options"][correct_index]
    user_answer = get_valid_answer()
    if user_answer == q["answer"]:
        print("Correct!")
        return 1
    else:
        print("Wrong. The correct answer was:", correct_text)
        return 0

3. Tracking Which Questions Were Wrong

You can keep a list of incorrectly answered questions and show them at the end.

def run_quiz(questions):
    print("Welcome to the quiz!")
    score = 0
    wrong_questions = []
    for q in questions:
        result = ask_question(q)
        if result == 1:
            score = score + 1
        else:
            wrong_questions.append(q["question"])
    total_questions = len(questions)
    percentage = (score / total_questions) * 100
    print()
    print("You scored", score, "out of", total_questions)
    print("Percentage:", round(percentage, 2), "%")
    if wrong_questions:
        print("\nYou missed these questions:")
        for wq in wrong_questions:
            print("-", wq)

Step 8: Possible Extensions (Ideas to Explore)

When you are comfortable with the basic version, you can extend your quiz using topics from other chapters:

  • Random order of questions (using random.shuffle() from the libraries chapter)
  • Load questions from a file (from the files chapter)
  • Timed quiz (using simple time functions)
  • Category-based quizzes (separate lists for different topics)
  • Difficulty levels (easy / medium / hard question sets)

Keep those ideas in mind as you continue the course; you can come back and improve your quiz as you learn more.


Summary

In this quiz application mini project you:

  • Designed a simple quiz flow
  • Created data structures to store questions and answers
  • Used loops and conditions to process user answers
  • Calculated a score and percentage
  • Organized the program with functions
  • Added small user-friendly features

You now have a complete, working console quiz that you can customize with your own questions and extend as your Python skills grow.

Views: 0

Comments

Please login to add a comment.

Don't have an account? Register now!

Where to Move

Move chapter:

  • ☰ 1. Chapter 1: What Is Programming?
    • ☰ 1.1. What is a computer program?
      • ☰ 1.2. What is Python?
        • ☰ 1.3. Where is Python used?
          • ☰ 1.4. How programming helps solve problems
            • ☰ 1.5. Your first Python program
            • ☰ 2. Chapter 2: Setting Up Python
              • ☰ 2.1. Installing Python (Windows / macOS / Linux)
                • ☰ 2.2. Using Python in the terminal
                  • ☰ 2.3. Using an IDE (IDLE / VS Code)
                    • ☰ 2.4. Running Python scripts
                      • ☰ 2.5. Python interactive mode
                      • ☰ 3. Chapter 3: Variables and Data Types
                        • ☰ 3.1. What is a variable?
                          • ☰ 3.2. Creating variables
                            • ☰ 3.3. Numbers
                              • ☰ 3.4. Test
                                • ☰ 3.5. Boolean values
                                  • ☰ 3.6. Type checking
                                  • ☰ 4. Chapter 4: Basic Operations
                                    • ☰ 4.1. Arithmetic operations
                                      • ☰ 4.2. Working with numbers
                                        • ☰ 4.3. String operations
                                          • ☰ 4.4. Combining text and variables
                                            • ☰ 4.5. Comments in Python
                                            • ☰ 5. Chapter 5: User Input and Output
                                              • ☰ 5.1. Getting input from the user
                                                • ☰ 5.2. Converting input to numbers
                                                  • ☰ 5.3. Formatting output
                                                    • ☰ 5.4. Writing interactive programs
                                                    • ☰ 6. Chapter 6: Conditions
                                                      • ☰ 6.1. Comparison operators
                                                        • ☰ 6.2. Logical operators
                                                          • ☰ 6.3. if, elif, else
                                                            • ☰ 6.4. Nested conditions
                                                              • ☰ 6.5. Common beginner mistakes
                                                              • ☰ 7. Chapter 7: Loops
                                                                • ☰ 7.1. Why loops are useful
                                                                  • ☰ 7.2. for loops
                                                                    • ☰ 7.3. while loops
                                                                      • ☰ 7.4. Loop counters
                                                                        • ☰ 7.5. break and continue
                                                                          • ☰ 7.6. Loop exercises
                                                                          • ☰ 8. Chapter 8: Data Collections
                                                                            • ☰ 8.1. Lists
                                                                              • ☰ 8.2. Tuples
                                                                                • ☰ 8.3. Dictionaries
                                                                                  • ☰ 8.4. Sets (basics)
                                                                                    • ☰ 8.5. Choosing the right data structure
                                                                                    • ☰ 9. Chapter 9: Functions
                                                                                      • ☰ 9.1. Why functions matter
                                                                                        • ☰ 9.2. Defining functions
                                                                                          • ☰ 9.3. Parameters and arguments
                                                                                            • ☰ 9.4. Return values
                                                                                              • ☰ 9.5. Scope (local vs global)
                                                                                                • ☰ 9.6. Reusing code
                                                                                                • ☰ 10. Chapter 10: Working with Files
                                                                                                  • ☰ 10.1. What is a file?
                                                                                                    • ☰ 10.2. Reading text files
                                                                                                      • ☰ 10.3. Writing and appending files
                                                                                                        • ☰ 10.4. File paths
                                                                                                          • ☰ 10.5. Simple file-based programs
                                                                                                          • ☰ 11. Chapter 11: Errors and Debugging
                                                                                                            • ☰ 11.1. Types of errors
                                                                                                              • ☰ 11.2. Reading error messages
                                                                                                                • ☰ 11.3. Common beginner errors
                                                                                                                  • ☰ 11.4. try and except
                                                                                                                    • ☰ 11.5. Debugging strategies
                                                                                                                    • ☰ 12. Chapter 12: Using Python Libraries
                                                                                                                      • ☰ 12.1. What is a library?
                                                                                                                        • ☰ 12.2. Importing modules
                                                                                                                          • ☰ 12.3. Standard libraries
                                                                                                                            • ☰ 12.3.1. math
                                                                                                                              • ☰ 12.3.2. random
                                                                                                                                • ☰ 12.3.3. datetime
                                                                                                                                • ☰ 12.4. Installing external libraries with pip
                                                                                                                                • ☰ 13. Chapter 13: Object-Oriented Programming
                                                                                                                                  • ☰ 13.1. What is object-oriented programming?
                                                                                                                                    • ☰ 13.2. Classes and objects
                                                                                                                                      • ☰ 13.3. The `__init__` method
                                                                                                                                        • ☰ 13.4. Attributes and methods
                                                                                                                                          • ☰ 13.5. Encapsulation
                                                                                                                                            • ☰ 13.6. Inheritance (basics)
                                                                                                                                              • ☰ 13.7. Simple OOP examples
                                                                                                                                              • ☰ 14. Chapter 14: Automation with Python
                                                                                                                                                • ☰ 14.1. What is automation?
                                                                                                                                                  • ☰ 14.2. Automating simple tasks
                                                                                                                                                    • ☰ 14.3. Working with files and folders
                                                                                                                                                      • ☰ 14.4. Automating text processing
                                                                                                                                                        • ☰ 14.5. Scheduling scripts
                                                                                                                                                          • ☰ 14.6. Practical automation examples
                                                                                                                                                          • ☰ 15. Chapter 15: Web Development with Python
                                                                                                                                                            • ☰ 15.1. How the web works (basic overview)
                                                                                                                                                              • ☰ 15.2. Introduction to Flask
                                                                                                                                                                • ☰ 15.3. Creating a simple web server
                                                                                                                                                                  • ☰ 15.4. Routing and templates
                                                                                                                                                                    • ☰ 15.5. Handling user input (forms)
                                                                                                                                                                      • ☰ 15.6. Very basic APIs
                                                                                                                                                                      • ☰ 16. Chapter 16: Data Science with Python
                                                                                                                                                                        • ☰ 16.1. What is data science?
                                                                                                                                                                          • ☰ 16.2. Working with data
                                                                                                                                                                            • ☰ 16.3. Introduction to NumPy
                                                                                                                                                                              • ☰ 16.4. Introduction to pandas
                                                                                                                                                                                • ☰ 16.5. Data visualization with matplotlib
                                                                                                                                                                                  • ☰ 16.6. Simple data analysis examples
                                                                                                                                                                                  • ☰ 17. Chapter 17: Mini Projects
                                                                                                                                                                                    • ☰ 17.1. Number guessing game
                                                                                                                                                                                      • ☰ 17.2. Simple calculator
                                                                                                                                                                                        • ☰ 17.3. To-do list
                                                                                                                                                                                          • ☰ 17.4. Password generator
                                                                                                                                                                                            • ☰ 17.5. Quiz application
                                                                                                                                                                                              • ☰ 17.6. Small web or data project
                                                                                                                                                                                              • ☰ 18. Chapter 18: Next Steps
                                                                                                                                                                                                • ☰ 18.1. How to practice Python
                                                                                                                                                                                                  • ☰ 18.2. Writing clean and readable code
                                                                                                                                                                                                    • ☰ 18.3. Choosing a specialization
                                                                                                                                                                                                      • ☰ 18.3.1. Web development
                                                                                                                                                                                                        • ☰ 18.3.2. Data science
                                                                                                                                                                                                          • ☰ 18.3.3. Automation
                                                                                                                                                                                                            • ☰ 18.3.4. Software development
                                                                                                                                                                                                            • ☰ 18.4. Learning resources and communities
                                                                                                                                                                                                            • ☰ 19. Appendix
                                                                                                                                                                                                              • ☰ 19.1. Python syntax cheat sheet
                                                                                                                                                                                                                • ☰ 19.2. Common errors and solutions
                                                                                                                                                                                                                  • ☰ 19.3. Glossary of terms