Build an AI Quiz Generator with Claude

Call the Claude API to generate and play a quiz on any topic.

Introduction

30 Second Summary

AI chatbots like Claude and ChatGPT can answer questions, write code, and explain complex topics. Behind every AI-powered app is a simple pattern: send a prompt to a language model and use the response to do something useful.

In this project, you will build a command-line quiz generator that calls Claude's API to create multiple-choice questions on any topic you choose.

What You'll Build

A Python script that sends structured prompts to Claude, parses JSON responses, and runs an interactive quiz game in your terminal.

By the end of this project, you'll have:

  • A working Python script that communicates with Claude's API to generate quiz questions on any topic.
  • A system prompt that controls how the LLM formats its responses as structured JSON.
  • An interactive terminal game that scores your answers and explains the correct ones.
  • Secret Mission: Add difficulty levels and a study mode that generates follow-up explanations for wrong answers.

Are there any prerequisites?

No prior experience is required. This guide walks you through installing Python, setting up your editor, and getting your API key from scratch.

Set Up Your Development Environment

Before you can build your AI-powered quiz generator, you need a few tools installed on your machine.

In this step, you'll install Python (the language your script will run on), set up a code editor, and create your project folder.

In this step, get ready to:
  • Install and verify Python 3.
  • Set up a code editor.
  • Create your project folder.
Install and verify Python 3

The Anthropic SDK (the library you'll use to talk to Claude) requires Python 3.9 or higher.

  • Check if Python 3 is already installed by running this command in your terminal:

How to open your terminal

Press Cmd+Space (macOS) or the Windows key (Windows) to open your search bar.

Type Terminal (macOS) or Command Prompt (Windows) and press Enter to open it.

macOS

python3 --version

Windows

python --version

✔️ I see Python 3.9 or higher

You're all set. Move on to the next substep.

ⓧ I see a version lower than 3.9

You need to upgrade to Python 3.9 or higher. The Anthropic SDK does not support older versions.

  • Visit python.org/downloads and download the latest Python 3 installer for your operating system.
  • Run the installer. On Windows, make sure to check Add Python to PATH before clicking Install Now.
  • Close and reopen your terminal, then run the version check command again.

macOS version shadowing

On macOS, the system python3 may still point to an older version after installing a new one. Try running python3.12 or python3.13 directly to use your newly installed version.

ⓧ Command not found

Python is not installed on your machine yet.

  • Visit python.org/downloads and download the latest Python 3 installer for your operating system.
  • Run the installer. On Windows, make sure to check Add Python to PATH before clicking Install Now.
  • Close and reopen your terminal, then run the version check command again to confirm it works.

Still seeing an error after installing?

On Windows, if the installer did not add Python to your PATH, uninstall and reinstall with the Add Python to PATH box checked.

On macOS, if python3 still points to an older version, try using the full versioned command like python3.12 or install a version manager like pyenv.

help me troubleshoot my Python installation

Set up your code editor

You need a code editor to write and save your Python files. VS Code is a popular free option that works on every platform.

✔️ I already have a code editor

If you already have VS Code, Cursor, Sublime Text, or any other code editor installed, you're good to go. Move on to the next substep.

ⓧ I need to install one

  • Visit code.visualstudio.com and download VS Code for your operating system.
  • Run the installer and follow the prompts to complete the installation.
  • Once installed, open VS Code by pressing Cmd+Space (macOS) or the Windows key (Windows), typing VS Code, and pressing Enter.
Create your project folder

Your project needs its own folder to keep all your files organized in one place.

  • Move to your Desktop by running this command:
cd ~/Desktop
  • Create your project folder and move into it by running these commands:
mkdir quiz-generator
cd quiz-generator
  • Confirm you're in the right place by running:
pwd

You should see a path ending in quiz-generator, such as /Users/yourname/Desktop/quiz-generator.

  • Open your code editor. Press Cmd+Space (macOS) or the Windows key (Windows), type VS Code, and press Enter.
  • In VS Code, click File in the top menu bar.
  • Click Open Folder.
  • Navigate to your Desktop, select the quiz-generator folder, then click Open.

Seeing a trust prompt?

VS Code may ask if you trust the authors of the files in this folder. Click Yes, I trust the authors to continue.

You should see the quiz-generator folder name in the Explorer sidebar on the left. The folder is empty for now.

Don't see the folder in VS Code?

Make sure you selected the quiz-generator folder itself, not a file inside it or the Desktop.

If the Explorer sidebar is hidden, click View in the top menu, then click Explorer to toggle it on.

help me open my project folder in VS Code

Your environment is ready to go. Next up, you'll create your Anthropic account and grab the API key that lets your script talk to Claude.

Get Your Claude API Key

Your development environment is ready. Now you need a way for your Python script to talk to Claude.

Every LLM application communicates through an API. To use Claude's API, you need an API key that identifies your account and authorizes your requests.

In this step, get ready to:
  • Create a free Anthropic account.
  • Generate an API key in the Anthropic Console.
  • Set the API key as an environment variable so your script can use it.
Create your Anthropic account

Anthropic is the company that builds Claude. You need a free account on their developer console to get an API key.

  • Open your browser and go to console.anthropic.com.
  • Click Sign Up to create a new account (or Log In if you already have one).
  • Complete the sign-up process using your email or a Google/GitHub account.

What is an API key?

An API key is a unique string that identifies you when your code sends requests to an external service. Think of it like a password that your script uses to prove it has permission to access Claude.

New Anthropic accounts receive a small amount of free credits to test the API. This project costs less than $0.01 in total, so the free credits are more than enough.

Generate your API key

Once you are logged in to the Anthropic Console, you need to create an API key for your project.

  • In the Console, click Settings and then navigate to the API Keys section.
  • Click the button to create a new API key.
  • Give your key a name like quiz-generator so you can identify it later.
  • Copy the key immediately and save it somewhere safe (like a notes app). You will not be able to see it again after closing the dialog.

Save your key before closing

Anthropic only shows your full API key once, at the moment of creation. If you close the dialog without copying it, you will need to create a new key.

Set the API key as an environment variable

The Anthropic Python SDK automatically looks for an environment variable called ANTHROPIC_API_KEY when it connects to the API. Setting this variable means your code never needs to contain the key directly.

  • Open the terminal inside VS Code by pressing Ctrl+` (macOS and Windows).
  • Set your API key as an environment variable by running the command for your operating system below.

macOS

  • Run this command, replacing your-api-key-here with the key you just copied:
export ANTHROPIC_API_KEY='your-api-key-here'

Windows

  • Run this command in Command Prompt, replacing your-api-key-here with the key you just copied:
set ANTHROPIC_API_KEY=your-api-key-here

Linux

  • Run this command, replacing your-api-key-here with the key you just copied:
export ANTHROPIC_API_KEY='your-api-key-here'

Why an environment variable?

Storing your API key in an environment variable keeps it out of your code files. This prevents you from accidentally sharing it if you publish your project to GitHub or send someone your code.

This variable lasts only for your current terminal session. If you close the terminal, you will need to set it again next time.

Not sure if it worked?

You will not see any output after running the export or set command. That is normal. The next step confirms everything is connected by making a real API call.

If you accidentally close this terminal window, you will need to run the export/set command again before your script can connect to Claude.

Help me troubleshoot my API key setup

Your API key is set and ready to go. In the next step, you will install the Anthropic SDK and make your first API call to confirm everything works.

Install the Anthropic SDK and Make Your First API Call

You have your API key ready and your environment configured. Now it's time to write actual Python code that talks to Claude.

Every Gen AI application follows the same core pattern: install the provider's SDK, create a client, send a message, and read the response. In this step, you'll prove that pattern works by sending your first message to Claude and seeing a response in your terminal.

In this step, get ready to:
  • Install the Anthropic Python SDK.
  • Write a test script that sends a message to Claude.
  • Run the script and confirm your API connection works.
Install the Anthropic Python SDK

The Anthropic Python SDK is a library that handles all the complexity of communicating with Claude's API. It manages authentication, request formatting, and response parsing so you can focus on what you want Claude to do.

  • In your terminal (the same session where you set ANTHROPIC_API_KEY), install the SDK by running this command:
pip install anthropic
  • You should see output ending with Successfully installed anthropic followed by a version number.

Seeing 'command not found'?

If pip is not recognized, try pip3 install anthropic instead. On some systems, Python 3's package manager uses the pip3 command.

help me fix a pip command not found error when installing the anthropic SDK

Create a test script

With the SDK installed, you can now write a short script that proves your API key works and that Claude can receive your messages.

  • In VS Code, create a new file called test_api.py inside your quiz-generator folder.
  • Paste the following code into test_api.py:
import anthropic

client = anthropic.Anthropic()

message = client.messages.create(
    model="claude-haiku-4-5",
    max_tokens=256,
    messages=[
        {"role": "user", "content": "Say hello!"}
    ],
)

print(message.content[0].text)

What does this code do?

  • import anthropic brings in the SDK you just installed.
  • anthropic.Anthropic() creates a client that automatically reads your ANTHROPIC_API_KEY environment variable for authentication.
  • client.messages.create(...) sends a message to Claude. You specify the model (claude-haiku-4-5), a token limit, and the conversation messages.
  • message.content[0].text extracts the text from Claude's response.

Why claude-haiku-4-5?

Claude Haiku 4.5 is Anthropic's fastest and most affordable model at $1 per million input tokens and $5 per million output tokens. For a quiz generator, it provides great quality at minimal cost. You can always swap to a more powerful model later by changing the model string.

  • Save test_api.py.
Run the script to confirm your connection
  • Run your test script by entering this command in your terminal:
python test_api.py
  • You should see a friendly greeting from Claude printed in your terminal. The exact wording varies each time, but it confirms your API connection is working.

Using python3 instead

If python doesn't work, try python3 test_api.py. Use whichever Python command worked when you verified your installation in Step 1.

Seeing an AuthenticationError?

This means your API key isn't being found. Make sure you're running the script in the same terminal session where you set ANTHROPIC_API_KEY. If you opened a new terminal window, you'll need to set the environment variable again.

help me fix an AuthenticationError when running my Anthropic API test script

✔️ Awesome, I've got everything!

Great. Double check you've saved your file before moving on.

ⓧ I'd like to double check the full code

import anthropic

client = anthropic.Anthropic()

message = client.messages.create(
    model="claude-haiku-4-5",
    max_tokens=256,
    messages=[
        {"role": "user", "content": "Say hello!"}
    ],
)

print(message.content[0].text)

Your API connection is confirmed and you've seen Claude respond to your first message. Next up, you'll build the quiz generator function that instructs Claude to produce structured quiz questions.

Build the Quiz Generator Function

In the previous step, you confirmed Claude responds to your prompts. Now it's time to build something useful with that connection.

The key to building applications on top of LLMs is controlling their output format. You'll write a function that uses a system prompt to make Claude respond with structured JSON quiz data that your Python code can parse and use.

In this step, get ready to:
  • Create quiz_generator.py with the generate_quiz() function.
  • Craft a system prompt that controls Claude's JSON output format.
  • Parse Claude's JSON response into usable Python data.
Create quiz_generator.py with the generate_quiz function

A system prompt is a special instruction you send to Claude alongside the user's message. It tells the model how to behave and what format to use for its response.

What is a system prompt?

Think of the system prompt as a job description for Claude. The user message says "what to do" while the system prompt says "how to do it." In your case, the system prompt tells Claude to always respond with valid JSON in a specific quiz question structure.

This is the foundational pattern behind every Gen AI application. You shape the model's output by giving it clear, structured instructions.

  • In VS Code, create a new file called quiz_generator.py inside your quiz-generator folder.
  • Paste the following code into quiz_generator.py:
import anthropic
import json


def generate_quiz(topic, num_questions=5):
    # Create the API client (reads ANTHROPIC_API_KEY from environment)
    client = anthropic.Anthropic()

    # Send the request with a system prompt that controls output format
    message = client.messages.create(
        model="claude-haiku-4-5",
        max_tokens=1024,
        system=(
            "You are a quiz generator. When given a topic, create multiple choice "
            "quiz questions. Respond ONLY with valid JSON in this exact format: "
            '{"questions": [{"question": "...", "options": ["A) ...", "B) ...", '
            '"C) ...", "D) ..."], "correct": "A", "explanation": "..."}]}'
        ),
        messages=[
            {
                "role": "user",
                "content": f"Create {num_questions} multiple choice quiz questions about: {topic}",
            }
        ],
    )

    # Extract the text and parse it as JSON
    response_text = message.content[0].text
    quiz_data = json.loads(response_text)
    return quiz_data["questions"]

What does this code do?

This function does three things in sequence:

  • anthropic.Anthropic() creates the API client. It reads your ANTHROPIC_API_KEY environment variable automatically.
  • The system parameter tells Claude to respond ONLY with JSON in a specific structure: each question has a question string, four options, a correct letter, and an explanation.
  • json.loads() parses Claude's text response into a Python dictionary so you can access each question as structured data.
  • Save quiz_generator.py.
  • Test the function by running this command in your terminal:
python3 -c "from quiz_generator import generate_quiz; questions = generate_quiz('science', 2); print(len(questions), 'questions generated')"

You should see 2 questions generated printed in your terminal. This confirms Claude received your system prompt, generated JSON, and your code parsed it successfully.

Seeing an error?

  • If you see ModuleNotFoundError: No module named 'anthropic', make sure you installed the SDK with pip install anthropic in the same terminal session.
  • If you see a JSON parsing error, run the command again. Occasionally the model may include extra text outside the JSON. A retry usually fixes it.
  • If you see an authentication error, confirm your ANTHROPIC_API_KEY environment variable is still set in your current terminal window. Environment variables reset when you close the terminal.

help me debug my quiz generator function

✔️ Awesome, I've got everything!

Great. Double check you've saved your file before moving on.

ⓧ I'd like to double check the full code

import anthropic
import json


def generate_quiz(topic, num_questions=5):
    client = anthropic.Anthropic()

    message = client.messages.create(
        model="claude-haiku-4-5",
        max_tokens=1024,
        system=(
            "You are a quiz generator. When given a topic, create multiple choice "
            "quiz questions. Respond ONLY with valid JSON in this exact format: "
            '{"questions": [{"question": "...", "options": ["A) ...", "B) ...", '
            '"C) ...", "D) ..."], "correct": "A", "explanation": "..."}]}'
        ),
        messages=[
            {
                "role": "user",
                "content": f"Create {num_questions} multiple choice quiz questions about: {topic}",
            }
        ],
    )

    response_text = message.content[0].text
    quiz_data = json.loads(response_text)
    return quiz_data["questions"]

Your quiz generator function is ready. Next up, you'll build the interactive quiz engine that turns these questions into a playable game in your terminal.

Build the Interactive Quiz Engine

Your generate_quiz() function can now fetch quiz questions from Claude on any topic. The data comes back as a clean list of dictionaries, each holding a question, options, the correct answer, and an explanation.

Now you need a way to present those questions to the user one at a time, accept their answers, and keep score. In this step, you'll build two functions that turn your raw data into a playable terminal quiz game.

In this step, get ready to:
  • Add a run_quiz() function that displays questions and tracks your score.
  • Add a main() function that ties the whole program together.
  • Run the script and play through a full quiz on any topic.
Add the run_quiz() function

This function takes the list of question dictionaries from generate_quiz() and turns them into an interactive experience. It loops through each question, collects the user's answer, and keeps a running score.

  • In quiz_generator.py, add the following run_quiz() function below the generate_quiz() function:
def run_quiz(questions):
    score = 0
    total = len(questions)

    print("\n" + "=" * 50)
    print("QUIZ TIME!")
    print("=" * 50)

    for i, q in enumerate(questions, 1):
        print(f"\nQuestion {i}/{total}:")
        print(q["question"])
        print()
        for option in q["options"]:
            print(f"  {option}")

        while True:
            answer = input("\nYour answer (A/B/C/D): ").strip().upper()
            if answer in ["A", "B", "C", "D"]:
                break
            print("Please enter A, B, C, or D.")

        if answer == q["correct"]:
            print("Correct!")
            score += 1
        else:
            print(f"Wrong! The correct answer was {q['correct']}.")
        print(f"Explanation: {q['explanation']}")

    print("\n" + "=" * 50)
    print(f"FINAL SCORE: {score}/{total} ({int(score / total * 100)}%)")
    print("=" * 50)

What does this code do?

  • score and total track how many the user gets right out of all questions.
  • The for loop uses enumerate(questions, 1) to number each question starting from 1.
  • The while True loop keeps asking for input until the user enters a valid letter (A, B, C, or D).
  • .strip().upper() cleans up the input so that lowercase answers and extra spaces still work.
  • After each answer, the function prints whether it was correct and shows the explanation Claude generated.

You won't see a change yet. The next chunk adds the main() function that ties everything together.

Add the main() function and entry point

The main() function is the conductor of your program. It asks the user what topic they want, calls generate_quiz() to get questions from Claude, then hands those questions to run_quiz().

  • Add the following code below your run_quiz() function in quiz_generator.py:
def main():
    print("AI-Powered Quiz Generator")
    print("-" * 30)

    topic = input("\nWhat topic would you like to be quizzed on? ")

    print(f"\nGenerating quiz questions about '{topic}'...")

    questions = generate_quiz(topic)
    run_quiz(questions)


if __name__ == "__main__":
    main()

What does this code do?

  • main() prints a header, prompts the user for a topic, then chains the two core functions together.
  • if __name__ == "__main__" is a Python pattern that runs main() only when you execute the file directly. It prevents the quiz from auto-running if you ever import this file into another script.
  • Save quiz_generator.py.

Seeing a syntax error when you save?

  • Make sure you left a blank line between the end of run_quiz() and the start of def main():. Python expects blank lines between top-level functions.
  • Check that the if __name__ line is NOT indented. It should be at the very left edge of the file, not inside any function.

Help me fix a syntax error in my quiz_generator.py file

✔️ Awesome, I've got everything!

Great. Double check you've saved your file before moving on.

ⓧ I'd like to double check the full code

Here is the complete quiz_generator.py file at this point:

import anthropic
import json


def generate_quiz(topic, num_questions=5):
    client = anthropic.Anthropic()

    message = client.messages.create(
        model="claude-haiku-4-5",
        max_tokens=1024,
        system=(
            "You are a quiz generator. When given a topic, create multiple choice "
            "quiz questions. Respond ONLY with valid JSON in this exact format: "
            '{"questions": [{"question": "...", "options": ["A) ...", "B) ...", '
            '"C) ...", "D) ..."], "correct": "A", "explanation": "..."}]}'
        ),
        messages=[
            {
                "role": "user",
                "content": f"Create {num_questions} multiple choice quiz questions about: {topic}",
            }
        ],
    )

    response_text = message.content[0].text
    quiz_data = json.loads(response_text)
    return quiz_data["questions"]


def run_quiz(questions):
    score = 0
    total = len(questions)

    print("\n" + "=" * 50)
    print("QUIZ TIME!")
    print("=" * 50)

    for i, q in enumerate(questions, 1):
        print(f"\nQuestion {i}/{total}:")
        print(q["question"])
        print()
        for option in q["options"]:
            print(f"  {option}")

        while True:
            answer = input("\nYour answer (A/B/C/D): ").strip().upper()
            if answer in ["A", "B", "C", "D"]:
                break
            print("Please enter A, B, C, or D.")

        if answer == q["correct"]:
            print("Correct!")
            score += 1
        else:
            print(f"Wrong! The correct answer was {q['correct']}.")
        print(f"Explanation: {q['explanation']}")

    print("\n" + "=" * 50)
    print(f"FINAL SCORE: {score}/{total} ({int(score / total * 100)}%)")
    print("=" * 50)


def main():
    print("AI-Powered Quiz Generator")
    print("-" * 30)

    topic = input("\nWhat topic would you like to be quizzed on? ")

    print(f"\nGenerating quiz questions about '{topic}'...")

    questions = generate_quiz(topic)
    run_quiz(questions)


if __name__ == "__main__":
    main()
Run the quiz and play through it

Your script is complete. Time to run it and play a full quiz.

  • Run your quiz generator by executing this command in your terminal:
python3 quiz_generator.py
  • When prompted, type a topic you'd like to be quizzed on (for example, Python basics or world history) and press Enter.
  • Answer each question by typing A, B, C, or D and pressing Enter.
  • Play through all 5 questions until you see your final score.

What should I see?

You should see a header saying "AI-Powered Quiz Generator", followed by a prompt asking for your topic. After you enter a topic, there will be a brief pause while Claude generates the questions. Then the quiz starts with a "QUIZ TIME!" banner.

Each question displays four options. After you answer, you see whether you were correct and an explanation. At the end, your final score appears as a fraction and percentage.

Quiz not working?

  • If you see a JSONDecodeError, Claude occasionally returns extra text around the JSON. Run the script again. The system prompt usually keeps Claude on track.
  • If you see an authentication error, confirm your ANTHROPIC_API_KEY environment variable is still set in your current terminal session. Opening a new terminal window resets it.
  • If you see ModuleNotFoundError: No module named 'anthropic', make sure you're using the same Python that you installed the SDK with. Try running python3 instead of python, or vice versa.

Help me debug my quiz generator script

Secret mission

Add Difficulty Levels and Study Mode

Your quiz generator works, but every quiz has the same challenge level. What if you could let the player choose how hard the questions are, and help them learn from their mistakes with AI-powered explanations?

Clean Up Your Resources

Clean Up Your Resources

This project runs locally and uses a pay-per-call API. There are no ongoing costs unless you run the script again.

Decide whether to keep your resources running, pause them to come back later, or delete them entirely.

Resources you used:

  • quiz-generator project folder (contains quiz_generator.py and test_api.py).
  • ANTHROPIC_API_KEY environment variable.
  • anthropic Python package.

Keep everything running

No action needed. Choose this if you want to keep experimenting with your quiz generator or plan to extend it with the Secret Mission.

  • Your project folder, environment variable, and installed package all stay in place.
  • The API only charges when you run the script, so there is no idle cost.

Pause - I'll come back to this later

Remove your API key from the environment to keep it secure while you are away. Your project files stay on disk for when you return.

  • Unset the environment variable by running this command in your terminal:

macOS

unset ANTHROPIC_API_KEY

Windows

set ANTHROPIC_API_KEY=
  • When you come back, re-export the variable using the same command from Step 2.

Delete - I don't want to use this again

Remove all project resources and start fresh. This removes your local files, the environment variable, and the installed package.

  • Unset the environment variable:

macOS

unset ANTHROPIC_API_KEY

Windows

set ANTHROPIC_API_KEY=
  • Uninstall the Anthropic Python package:
pip uninstall anthropic
  • Delete the project folder:

macOS

rm -rf ~/Desktop/quiz-generator

Windows

rmdir /s /q %USERPROFILE%\Desktop\quiz-generator
  • Optionally, delete or revoke your API key in the Anthropic Console under the API Keys section.

That's a Wrap!

That's a Wrap!

Nice work! You just built a fully interactive quiz game powered by Claude's API. Type in any topic and your script generates questions, runs the quiz, and scores your answers.

Here's what you learned:

  • Built a Python application that sends prompts to an LLM and processes structured JSON responses.
  • Crafted a system prompt that controls Claude's output format, the foundational pattern behind every Gen AI application.
  • Created a complete terminal quiz engine with user input handling and score tracking.
  • Added difficulty levels and an AI-powered study mode that generates follow-up explanations for wrong answers.

Ready to quiz yourself?