Python and SQLite: Building a Quiz Application Exercise

Table of Contents

  1. Introduction
  2. Prerequisites
  3. Installing SQLite
  4. Setting Up the Quiz Database
  5. Creating the Quiz Application
  6. Conclusion

Introduction

In this tutorial, we will build a quiz application using Python and SQLite. The quiz application will allow users to answer questions and provide feedback on their performance. By the end of this tutorial, you will have a working quiz application that you can customize and expand upon.

Prerequisites

To follow this tutorial, you should have a basic understanding of Python programming concepts. It is recommended to have Python 3.x installed on your machine.

Installing SQLite

SQLite is a lightweight database engine that allows us to store and query data. To install SQLite, follow these steps:

  1. Visit the SQLite download page at https://sqlite.org/download.html

  2. Download the precompiled binaries for your operating system (e.g., Windows, macOS, Linux)

  3. Install the downloaded binaries by running the installer

  4. Verify the installation by opening a command prompt or terminal and entering the following command:

    sqlite3 --version
    

    The command should display the version number if the installation was successful.

Setting Up the Quiz Database

Before we can start building the quiz application, we need to set up the database that will store the quiz questions and answers. Follow these steps:

  1. Create a new directory for your project and navigate to it using the command prompt or terminal.

  2. Create a new file called quiz.db using the following command:

    sqlite3 quiz.db
    
  3. Once the SQLite shell opens, run the following commands to create a table for the quiz questions:

    CREATE TABLE questions (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        question TEXT,
        correct_answer TEXT,
        incorrect_answers TEXT
    );
    
  4. Exit the SQLite shell by entering .exit or pressing Ctrl + D.

Creating the Quiz Application

Now that we have set up the database, we can start building the quiz application. Follow these steps:

  1. Create a new Python script called quiz.py in your project directory.

  2. Open the quiz.py file in your favorite text editor and import the necessary modules:

    import sqlite3
    import random
    
  3. Establish a connection to the SQLite database and create a cursor:

    connection = sqlite3.connect('quiz.db')
    cursor = connection.cursor()
    
  4. Create a function to retrieve a random question from the database:

    def get_random_question():
        cursor.execute("SELECT * FROM questions ORDER BY RANDOM() LIMIT 1")
        question = cursor.fetchone()
        return question
    

    In this function, we use the RANDOM() function provided by SQLite to retrieve a random question from the database.

  5. Create a function to prompt the user for an answer and check its correctness:

    def prompt_user(question):
        print(question[1])
        answers = question[3].split(',') + [question[2]]
        random.shuffle(answers)
    
        for index, answer in enumerate(answers):
            print(f"{index+1}. {answer}")
    
        user_answer = input("Enter your answer: ")
        correct_answer = question[2]
    
        if answers[int(user_answer)-1] == correct_answer:
            print("Correct!")
        else:
            print(f"Wrong! The correct answer is {correct_answer}")
    

    In this function, we first print the question and shuffle the answers. We then prompt the user to enter their answer and compare it with the correct answer from the database.

  6. Create a function to run the quiz:

    def run_quiz(num_questions):
        for _ in range(num_questions):
            question = get_random_question()
            prompt_user(question)
            print()
    
    run_quiz(5)  # Run the quiz with 5 questions
    

    In this function, we use a loop to iterate a given number of times and retrieve a random question from the database, then prompt the user for an answer.

  7. Close the database connection once the quiz is complete:

    connection.close()
    

    This step ensures that the database resources are properly released.

Conclusion

In this tutorial, you learned how to build a quiz application using Python and SQLite. You learned how to set up the quiz database, retrieve random questions, prompt the user for answers, and check the correctness of their responses. You can further customize and expand this quiz application by adding more questions, implementing a scoring system, or creating a user interface. Have fun exploring and enhancing your quiz application!