Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Here is an example of how to create a Python quiz using JSON with only one question and the quiz stops after it:

  1. Create a JSON file with the following content:
{
  "question": "What is the national animal of Australia?",
  "options": [
    "Kangaroo",
    "Koala",
    "Emu",
    "Platypus"
  ],
  "answer": "Kangaroo"
}
  1. Import the json module and read the JSON file:
import json

with open("quiz.json") as f:
    quiz_data = json.load(f)
  1. Print the question and options:
print(quiz_data["question"])
for option in quiz_data["options"]:
    print(option)
  1. Get the user's answer to the question:
user_answer = input("Your answer: ")
  1. Check if the user's answer is correct or not:
if user_answer == quiz_data["answer"]:
    print("Correct!")
else:
    print("Incorrect!")
  1. Exit the quiz:
exit()

The complete code looks like this:

import json

with open("quiz.json") as f:
    quiz_data = json.load(f)

print(quiz_data["question"])
for option in quiz_data["options"]:
    print(option)

user_answer = input("Your answer: ")

if user_answer == quiz_data["answer"]:
    print("Correct!")
else:
    print("Incorrect!")

exit()

Note: This quiz only has one question, so it will stop after the user answers it. If you want to create a quiz with multiple questions, you will need to modify the code accordingly.