Ask Your Question
4

How can I create a Python quiz using Json with only one question and the quiz stops after it?

asked 2022-12-20 11:00:00 +0000

devzero gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2023-03-27 03:00:00 +0000

qstack gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-12-20 11:00:00 +0000

Seen: 9 times

Last updated: Mar 27 '23