Build an AI-Powered Quiz Game
Use Python and Google Gemini API to build a quiz game on any topic.
Introduction
30 Second Summary
Everyone loves a good quiz. Whether it's testing yourself before an exam or settling a debate with friends, quizzes turn learning into a game.
In this project, you will build a command-line quiz game in Python that connects to Google's Gemini AI. You pick any topic, and the AI generates unique multiple-choice questions, grades your answers, and explains the correct answer so you learn as you play.
What You'll Build
A quiz game you can run in your terminal, type any topic from "dinosaurs" to "quantum physics," and instantly get fresh AI-generated questions with explanations for every answer.
By the end of this project, you'll have:
- A working Python script that sends prompts to an AI model and receives structured responses you can use directly in your code.
- An interactive game loop that displays questions, collects your answers, shows explanations, and tracks your score from start to finish.
- A reusable function that generates quiz data in clean JSON format on any topic you choose.
- Secret Mission: Add difficulty levels and a hint system so you can control how hard the AI makes your questions.
Are there any prerequisites?
None. This guide walks you through installing Python, setting up your API key, and writing every line of code from scratch. All you need is a computer with VS Code installed.
Before We Start
Before we dive in, let's lock in what you're about to build and why it matters.
Taking a moment to commit to the goal helps you stay focused through each step of the build.
Set Up Your Tools
To build your AI-powered quiz game, you need three things: Python to write the code, Google's AI SDK to communicate with the Gemini model, and an API key that grants you access to the AI.
In this step, you'll install all three and confirm everything connects properly.
In this step, get ready to:
- Install Python on your computer.
- Install the Google GenAI SDK and get your API key.
- Test the connection with a starter script.
Install Python
Python is the programming language you'll write your quiz game in. The Google GenAI SDK requires Python 3.10 or higher.
- Open a terminal inside VS Code by pressing Cmd+` (macOS) or Ctrl+` (Windows).
- Check if Python is already installed by running this command:
macOS
python3 --version
Windows
python --version
✔️ I see version 3.10 or higher
You're all set. Move on to the next substep.
ⓧ I see an older version
You have Python installed, but it's too old for this project. Download the latest version.
- Go to python.org/downloads in your browser.
- Click the download button for Python 3.14.
- Run the installer.
- On Windows: check the box labeled Add python.exe to PATH before clicking Install Now.
- Close and reopen your VS Code terminal after installation completes.
- Run the version check command again to confirm it now shows 3.10 or higher.
Why close and reopen the terminal?
Your terminal loads PATH settings when it first opens. A new install updates PATH, but the existing terminal still has the old settings. Reopening it picks up the fresh PATH.
ⓧ Command not found
Python isn't installed yet. Let's set it up from scratch.
- Go to python.org/downloads in your browser.
- Click the download button for Python 3.14.
- Run the installer.
- On Windows: check the box labeled Add python.exe to PATH before clicking Install Now.
- Close and reopen your VS Code terminal after installation completes.
- Run the version check command again to confirm you see a version number.
This checkbox is critical
If you skip the Add python.exe to PATH checkbox, your terminal won't recognize the python command. You would need to uninstall and reinstall Python with the checkbox enabled.
Still getting command not found after installing?
- Make sure you closed and reopened the VS Code terminal after installing Python.
- On macOS, the command is python3 not python. Try python3 --version instead.
- If you're on Windows and skipped the PATH checkbox, uninstall Python from Settings > Apps and reinstall with the checkbox enabled.
Why isn't Python recognized in my terminal after installing?
Install the Google GenAI SDK and get your API key
The google-genai SDK is the Python library that lets your code talk to Google's Gemini AI model.
- Install the SDK by running this command in your VS Code terminal:
macOS
pip3 install google-genai
Windows
pip install google-genai
You should see output ending with a line that says Successfully installed followed by package names.
Seeing a pip not found error?
- On macOS, try pip3 instead of pip.
- On Windows, if pip is not recognized, Python's PATH was not set correctly. Revisit the Python install step above.
Why is pip not working even though I installed Python?
Now you need an API key to authenticate with Google's AI. The Gemini API has a free tier with no credit card required.
- Open aistudio.google.com in your browser.
- Sign in with your Google account.
- Click Get API Key in the left sidebar.
- Google AI Studio automatically creates an API key for new users. Copy the key shown on the API keys page.
- Save this key somewhere safe. You'll paste it into your code in the next substep.
What is an API key?
An API key is like a password that identifies your app to Google's servers. It tells Google who is making the request so they can track your usage against the free tier limits.
Keep your key private. Do not share it publicly or commit it to a public code repository.
Free tier means zero cost
The Gemini API free tier gives you free input and output tokens with no credit card required and no expiration. This entire project costs nothing to run.
Test the connection
You have Python and the SDK installed, and you have your API key. Now let's confirm everything works together.
- In VS Code, create a new file by pressing Cmd+N (macOS) or Ctrl+N (Windows).
- Save the file immediately as quiz_game.py by pressing Cmd+S (macOS) or Ctrl+S (Windows). Save it to your Desktop.
- Add the following starter code to quiz_game.py:
import json
from google import genai
from google.genai import types
# Create a client that connects to Google's Gemini AI
client = genai.Client(api_key="your-api-key-here")
- Replace your-api-key-here with the API key you copied from Google AI Studio. Keep the quotes around it.
- Save the file.
What does this code do?
- import json loads Python's built-in JSON library. You'll use this later to parse AI responses.
- from google import genai imports the Google GenAI SDK you just installed.
- from google.genai import types imports configuration types you'll use in later steps.
- genai.Client(api_key=...) creates a client object that handles communication with Google's AI servers using your key.
Before you run this, what do you expect to happen? If everything is set up correctly, Python should run the file and return to the prompt with no output and no errors.
- Make sure your terminal is in the same folder as quiz_game.py. If you saved to your Desktop, navigate there by running:
macOS
cd ~/Desktop
Windows
cd Desktop
- Run your script:
macOS
python3 quiz_game.py
Windows
python quiz_game.py
The command should finish and return you to the terminal prompt with no error messages. No output is expected because the script only creates a client object without making any API calls yet.
Seeing an error?
- ModuleNotFoundError: No module named 'google' means the SDK didn't install correctly. Run the pip install google-genai command again.
- SyntaxError means you have a typo in the code. Double check that your quotes and parentheses match the code above.
- If you see No such file or directory, your terminal is not in the same folder as your file. Run the cd command above first.
My script is throwing an error when I try to run it. What's wrong?
✔️ Awesome, I've got everything!
Great. Double check you've saved quiz_game.py and your terminal returned with no errors.
ⓧ I'd like to double check the full code
Here's the complete quiz_game.py file at this point:
import json
from google import genai
from google.genai import types
client = genai.Client(api_key="your-api-key-here")
Your tools are locked in. Python, the SDK, and your API key are all working together. Next up, you'll send your first message to the AI and see it respond.
Talk to the AI
Your tools are set up and Python can reach Google's servers without errors. Now it's time to make the AI actually respond to you.
Every AI-powered application follows one core loop: you send a prompt to a model, and it sends a response back. In this step, you'll see that loop working firsthand.
In this step, get ready to:
- Send a prompt to the Gemini AI model and print its response.
- Observe how quiz-related prompts come back as unstructured text that is hard to parse.
Send your first prompt
The method client.models.generate_content() is how you talk to Gemini. You pass it a model name and the contents of your prompt, and it returns the AI's response.
- In VS Code, open quiz_game.py.
- Below the client = genai.Client(...) line, add the following code to send a question to the AI and print its answer:
# Send a prompt to the AI model and print the response
response = client.models.generate_content(
model="gemini-3.5-flash",
contents="What is the largest planet in our solar system?"
)
print(response.text)
What does this code do?
- client.models.generate_content() sends your prompt to Google's AI servers and waits for a response.
- model="gemini-3.5-flash" tells the SDK which AI model to use.
- contents is your prompt. This is the text the AI reads and responds to.
- response.text holds the AI's answer as a plain text string.
- Save quiz_game.py.
- Run the file by entering this command in your VS Code terminal:
python quiz_game.py
You should see the AI's answer about Jupiter printed in your terminal. The exact wording varies each time because the AI generates fresh responses.
Seeing an error instead of a response?
- If you see API key not valid. Please pass a valid API key. then your API key in the code is incorrect. Return to Google AI Studio, copy your key again, and paste it between the quotes on the api_key= line.
- If you see ModuleNotFoundError: No module named 'google' then the SDK is not installed in your current Python environment. Run pip install google-genai again.
- If your region is not supported by the free tier, you may see a 400 FAILED_PRECONDITION error. Check the Gemini API documentation for supported regions.
Still stuck? Help me debug my first Gemini API call in Python.
Experiment with different prompts
You just proved the AI can answer a simple factual question. Now try asking it for something your quiz game will actually need: multiple quiz questions about a topic.
- In quiz_game.py, find the contents line inside generate_content():
contents="What is the largest planet in our solar system?"
- Replace that line with this new prompt asking for quiz questions:
contents="Give me 3 quiz questions about space"
- Save quiz_game.py.
Before you run this, think about what you expect. If the AI gives you quiz questions as a block of text, how would your Python code reliably figure out where one question ends and the next begins?
- Run the file again:
python quiz_game.py
The AI responds with quiz questions, but they come back as a wall of text. Some questions might be numbered, others bulleted, and the format changes every time you run it.
This is the core problem. You cannot reliably split this freeform text into individual questions, answer options, and correct answers using Python string methods.
Why is unstructured text a problem?
Your quiz game needs to display one question at a time, show specific answer options, and check if the player picked the right one. To do that, your code needs data it can index into: a list of questions, each with labeled fields.
Plain text gives you none of that. In the next step, you'll tell the AI exactly what shape of data to return so Python can work with it directly.
✔️ Awesome, I've got everything!
Great. Double check you've saved quiz_game.py with the quiz questions prompt.
ⓧ I'd like to double check the full code
Here is what your complete quiz_game.py should look like right now:
import json
from google import genai
from google.genai import types
client = genai.Client(api_key="your-api-key-here")
response = client.models.generate_content(
model="gemini-3.5-flash",
contents="Give me 3 quiz questions about space"
)
print(response.text)
You've proven the core AI loop works: prompt in, response out. Next up, you'll solve the messy-text problem by telling the AI to respond in clean, structured JSON that Python can work with directly.
Get Structured Data from the AI
In the last step, you asked the AI for quiz questions and got back a wall of text. You could read it yourself, but your Python program has no reliable way to split that text into individual questions, options, and answers.
The fix is to tell the AI exactly what shape of data you want back. In this step, you will use a JSON schema to force the AI to return clean, structured data that Python can work with directly.
In this step, get ready to:
- Define a JSON schema that describes quiz question data.
- Configure the AI to return structured JSON instead of plain text.
- Test your function with different topics to confirm it generates unique questions each time.
Define a JSON schema for quiz questions
A JSON schema is a blueprint that describes the exact structure of data you expect. By passing a schema to the AI, you force it to return data in a predictable format your code can parse.
- In quiz_game.py, find everything below the client = genai.Client(...) line.
- Delete the response = client.models.generate_content(...) block and the print(response.text) line.
- In their place, paste this code that starts a new function and defines the schema:
def generate_questions(topic, num_questions=3):
# Define the exact JSON structure the AI must follow
quiz_schema = {
"type": "object",
"properties": {
"questions": {
"type": "array",
"items": {
"type": "object",
"properties": {
"question": {"type": "string"},
"options": {
"type": "array",
"items": {"type": "string"}
},
"correct_answer": {"type": "string"},
"explanation": {"type": "string"}
},
"required": ["question", "options", "correct_answer", "explanation"]
}
}
},
"required": ["questions"]
}
What does this code do?
- generate_questions(topic, num_questions=3) creates a reusable function that accepts any topic and an optional number of questions (defaulting to 3).
- quiz_schema is a dictionary describing the exact shape of data the AI must return: an array of question objects, each with a question string, an options array, a correct_answer string, and an explanation string.
- The required arrays ensure the AI never skips a field.
- Save quiz_game.py.
Request structured output from the AI
Now you will add the API call inside the function, telling the AI to respond in JSON matching your schema.
- Directly below the closing } of quiz_schema (still inside the function), paste this code:
# Send prompt to AI with structured output config
response = client.models.generate_content(
model="gemini-3.5-flash",
contents=f"Generate {num_questions} multiple choice quiz questions about {topic}. Each question should have 4 options labeled A, B, C, D. The correct_answer should be just the letter (A, B, C, or D).",
config=types.GenerateContentConfig(
response_mime_type="application/json",
response_json_schema=quiz_schema,
),
)
# Parse the JSON string into a Python dictionary
return json.loads(response.text)
# Test the function
print(generate_questions("space"))
What does this code do?
- response_mime_type="application/json" forces the AI to return valid JSON instead of free-form text.
- response_json_schema=quiz_schema gives the AI your blueprint so it knows the exact structure to follow.
- json.loads(response.text) converts the JSON string from the AI into a Python dictionary you can loop through.
- The f-string prompt includes {num_questions} and {topic} so the same function works for any subject.
Before you run this, what do you think the output will look like compared to the wall of text you saw in Step 2?
- Save quiz_game.py and run it:
python quiz_game.py
You will see a Python dictionary with neatly organized keys like question, options, correct_answer, and explanation instead of a wall of unstructured text.
Seeing an error instead of quiz data?
- If you see IndentationError: make sure the response = client.models.generate_content(...) block is indented one level inside the function, matching the same level as quiz_schema.
- If you see NameError: name 'generate_questions' is not defined: check that print(generate_questions("space")) is outside the function (no indentation), not inside it.
- If you see User location is not supported for the API use: the Gemini API free tier is not available in all regions. Check whether your country is on the supported regions list at ai.google.dev.
Help me debug my JSON schema error
Test with different topics
Your function accepts any topic as an argument. Each time you call it, the AI generates completely fresh questions.
- Run python quiz_game.py again without changing anything:
python quiz_game.py
Even with the same topic, the AI generates different questions each time. This is the power of having a reusable function with structured output.
Try other topics
Change "space" in the print(generate_questions("space")) line to any topic you like. Try "cooking" or "history" and run again to see completely different quiz questions.
✔️ Awesome, I've got everything!
Great. Double check you have saved quiz_game.py and that running it prints structured quiz data.
ⓧ I'd like to double check the full code
Your quiz_game.py should contain these sections in this order. Scroll up and confirm each one is present:
- The three import lines (json, genai, types) at the top.
- The client = genai.Client(api_key="your-api-key-here") line (with your real key).
- The def generate_questions(topic, num_questions=3): function definition.
- Inside the function: the quiz_schema dictionary.
- Inside the function: the client.models.generate_content(...) call with config=types.GenerateContentConfig(...).
- Inside the function: return json.loads(response.text).
- Outside the function: print(generate_questions("space")).
You now have a function that takes any topic and gets back clean, structured quiz data from the AI. Next up, you will turn this into a playable game with scoring and feedback.
Build the Interactive Game
In the last step, you taught the AI to return structured JSON data instead of a wall of text. Your generate_questions() function can now produce clean quiz data on any topic, ready for Python to work with.
Now comes the fun part. You will connect that data to a real game loop where a player picks a topic, answers questions, and gets scored. This is where your quiz game comes alive.
In this step, get ready to:
- Build a game loop that asks the player for a topic and displays AI-generated questions.
- Add scoring and feedback so the player knows how they did after each question.
- Display a final score with a performance message at the end of the game.
Create the game loop
Right now, your file ends with a test line that prints raw quiz data. You will replace that with a proper game function that asks the player for a topic, generates questions, and presents them one by one.
- In quiz_game.py, scroll to the bottom of your file.
- Find this line:
print(generate_questions("space"))
- Delete that entire line. You will replace it with the game function next.
- Add the following code below the generate_questions() function (where the old print line was):
def play_quiz():
# Display the game header
print("=" * 40)
print(" AI-POWERED QUIZ GAME")
print("=" * 40)
print()
# Ask the player for a topic and generate questions
topic = input("What topic would you like to be quizzed on? ")
print(f"\nGenerating questions about '{topic}'...\n")
quiz_data = generate_questions(topic)
questions = quiz_data["questions"]
score = 0
# Loop through each question and collect answers
for i, q in enumerate(questions, 1):
print(f"Question {i}: {q['question']}")
print()
for option in q["options"]:
print(f" {option}")
print()
answer = input("Your answer (A/B/C/D): ").strip().upper()
if __name__ == "__main__":
play_quiz()
What does this code do?
This creates a play_quiz() function that runs the game from start to finish.
- input() pauses the program and waits for the player to type something.
- The for loop walks through each question in the list, displaying it with numbered options.
- .strip().upper() cleans up the player's input so "b", " B ", and "B" all work the same way.
- if __name__ == "__main__": ensures play_quiz() runs when you execute the file directly.
- Save quiz_game.py.
- Run the game by entering this command in your terminal:
python quiz_game.py
Type a topic when prompted (like "space" or "cooking"). You should see the game header, your topic acknowledged, then numbered questions with A/B/C/D options appearing one at a time.
Type an answer letter for each question. The game moves to the next question each time, but you will not see any feedback yet. That comes next.
Not seeing any questions?
- Make sure you deleted the old print(generate_questions("space")) line. Having both that line and the new function can cause confusion.
- Check that if __name__ == "__main__": is at the very bottom of the file with no indentation.
- Confirm your API key is still set correctly in the client line at the top of the file.
Still stuck? Help me debug why my quiz game isn't displaying questions when I run it.
Add scoring and feedback
The game asks questions, but the player gets no feedback. You need to compare their answer to the correct one, tell them if they got it right, and show the explanation after each question.
- In quiz_game.py, find the answer = input("Your answer (A/B/C/D): ").strip().upper() line inside the for loop.
- Add the following code directly below that line, still inside the for loop (keep the same indentation level):
# Check if the answer is correct
if answer == q["correct_answer"].strip().upper():
print("Correct!")
score += 1
else:
print(f"Incorrect! The answer was {q['correct_answer']}.")
# Show the explanation after each question
print(f"Explanation: {q['explanation']}")
print()
What does this code do?
- The if/else compares the player's answer to the AI's correct_answer field from the structured JSON data.
- score += 1 adds a point for each correct answer, building up the player's total.
- The explanation prints after every question, so the player learns regardless of whether they got it right.
Now add the final score display. This code goes after the for loop ends, still inside the play_quiz() function (one level of indentation, aligned with the for keyword).
- Add this code below the for loop (after the last print() inside the loop, dedent one level):
# Display the final score
print("=" * 40)
print(f" FINAL SCORE: {score}/{len(questions)}")
print("=" * 40)
# Show a performance message based on score
if score == len(questions):
print(" Perfect score! You're an expert!")
elif score >= len(questions) // 2:
print(" Good job! Keep learning!")
else:
print(" Keep practicing, you'll get better!")
What does this code do?
- After all questions are answered, the game displays the total score out of the number of questions.
- len(questions) // 2 calculates half the total (integer division), so the messages adjust based on how well the player did.
- Save quiz_game.py.
Before you run this, what do you think will happen when you answer a question correctly versus incorrectly?
- Run the full game by entering this command:
python quiz_game.py
Type a topic, answer 3 questions, and watch the scoring in action. After each answer you will see "Correct!" or "Incorrect!" with the explanation. At the end, your final score appears with a performance message.
Seeing an indentation error?
- The scoring logic (the if answer == block) must be indented with 8 spaces, inside the for loop.
- The final score display (the print("=" * 40) block) must be indented with 4 spaces, outside the for loop but still inside play_quiz().
- Make sure you are not mixing tabs and spaces. VS Code shows this as a squiggly underline.
Need help? Help me fix my Python indentation error in the quiz game scoring logic.
✔️ Awesome, I've got everything!
Great. Make sure you have saved quiz_game.py before moving on.
ⓧ I'd like to double check the full code
Your quiz_game.py should contain these sections in order. Scroll through your file and confirm each one is present:
- The import statements and client = genai.Client(...) line at the top.
- The generate_questions(topic, num_questions=3) function with the quiz schema and AI call.
- The play_quiz() function containing: the game header, topic input(), the question display loop, scoring logic, and final score display.
- The if __name__ == "__main__": block calling play_quiz() at the very bottom.
Make sure there is no leftover print(generate_questions("space")) line anywhere in the file.
Your quiz game is fully playable. You can run it anytime to test yourself on any subject, and the AI generates fresh questions every time. Next up, you will take on the Secret Mission and add difficulty levels with a hint system to make the game even more engaging.
Secret mission
Add Difficulty and Hints
Your quiz game works, but every question is the same level of challenge. What if you could pick easy, medium, or hard? What if you could ask for a hint when you're stuck? In this secret mission, you'll add both features by changing how you talk to the AI.
Clean Up Your Resources
Clean Up Your Resources
This project runs entirely locally and uses Google's free tier API, so there are no ongoing costs. Decide whether to keep your resources running, pause them to come back later, or delete them entirely.
Resources you used:
- quiz_game.py file on your Desktop.
- google-genai Python package (installed via pip).
- Google AI Studio API key.
Keep everything running
No action needed. Choose this if you plan to keep building AI projects with Python and the Gemini API.
- Your API key stays active on Google's free tier with no charges.
- Your quiz_game.py file stays on your Desktop ready to run anytime.
- The google-genai package stays installed for future projects.
Pause - I'll come back to this later
Nothing to pause. Your API key has no expiration and costs nothing while idle. Your local files take negligible disk space.
- You can come back and run python quiz_game.py anytime without any reactivation steps.
Delete - I don't want to use this again
Remove all project resources and revoke your API key. Follow each step below.
- Delete your project file by running this command in the VS Code terminal:
del %USERPROFILE%\Desktop\quiz_game.py
- Uninstall the Google GenAI SDK by running:
pip uninstall google-genai
- Type y when prompted to confirm the uninstall.
- To revoke your API key, go to aistudio.google.com and open the API keys page.
- Find your key, click the trash icon next to it, and confirm deletion.
That's a Wrap!
That's a Wrap!
Nice work! You just built a fully interactive AI-powered quiz game in Python that generates unique questions on any topic you choose.
You've learned how to:
- Connect Python to a large language model using the Google Gemini API free tier, following the fundamental pattern of AI development: prompt in, structured response out.
- Request and parse structured JSON responses from an AI model into usable Python data, using a schema to control the exact shape of what comes back.
- Control AI behavior through prompt engineering, changing topics, difficulty, and output format just by adjusting the text you send.
- Secret Mission: Added difficulty levels and a hint system that demonstrates how prompt changes directly affect AI output.
Ready to quiz yourself?