make a program to upload mcq qestions in a jason file and then allow users to attempt test
- User
make a program to upload mcq qestions in a jason file and then allow users to attempt test
- Assistant
make a program to upload mcq qestions in a jason file and then allow users to attempt test
Certainly! Below is a Python program that allows you to:
First, let's define the structure of the JSON file (questions.json) that will store the MCQ questions:
[
{
"question": "What is the capital of France?",
"options": ["Paris", "London", "Berlin", "Madrid"],
"answer": "Paris"
},
{
"question": "Which language is primarily used for Android app development?",
"options": ["Swift", "Kotlin", "Ruby", "JavaScript"],
"answer": "Kotlin"
}
// ... more questions
]
Each question entry consists of:
question: The MCQ question.options: A list of possible answers.answer: The correct answer.Here's the complete Python program that handles adding questions and taking the test:
import json
import os
# Path to the JSON file
JSON_FILE = 'questions.json'
def load_questions():
"""Load questions from the JSON file."""
if not os.path.exists(JSON_FILE):
return []
with open(JSON_FILE, 'r', encoding='utf-8') as file:
try:
return json.load(file)
except json.JSONDecodeError:
return []
def save_questions(questions):
"""Save questions to the JSON file."""
with open(JSON_FILE, 'w', encoding='utf-8') as file:
json.dump(questions, file, indent=4)
def add_question():
"""Add a new MCQ to the JSON file."""
print("\n--- Add a New Question ---")
question_text = input("Enter the question: ").strip()
options = []
num_options = 4 # Assuming 4 options per question
for i in range(1, num_options + 1):
option = input(f"Enter option {i}: ").strip()
options.append(option)
while True:
answer = input("Enter the correct answer: ").strip()
if answer in options:
break
else:
print("Answer must be one of the provided options. Please try again.")
new_question = {
"question": question_text,
"options": options,
"answer": answer
}
questions = load_questions()
questions.append(new_question)
save_questions(questions)
print("Question added successfully!\n")
def attempt_test():
"""Allow user to attempt the test."""
print("\n--- Attempt the Test ---")
questions = load_questions()
if not questions:
print("No questions available. Please add questions first.\n")
return
score = 0
for idx, q in enumerate(questions, 1):
print(f"\nQuestion {idx}: {q['question']}")
for opt_num, option in enumerate(q['options'], 1):
print(f" {opt_num}. {option}")
while True:
try:
choice = int(input("Your answer (enter the option number): "))
if 1 <= choice <= len(q['options']):
selected_option = q['options'][choice - 1]
if selected_option == q['answer']:
print("Correct!")
score += 1
else:
print(f"Wrong! The correct answer is: {q['answer']}")
break
else:
print(f"Please enter a number between 1 and {len(q['options'])}.")
except ValueError:
print("Invalid input. Please enter a number.")
print(f"\nTest Completed! Your score: {score}/{len(questions)}\n")
def list_questions():
"""List all questions (for reference)."""
questions = load_questions()
if not questions:
print("\nNo questions available.\n")
return
print("\n--- List of Questions ---")
for idx, q in enumerate(questions, 1):
print(f"{idx}. {q['question']}")
print()
def main_menu():
"""Display the main menu and handle user choices."""
while True:
print("=== MCQ Test Application ===")
print("1. Add a Question")
print("2. Attempt Test")
print("3. List All Questions")
print("4. Exit")
choice = input("Select an option (1-4): ").strip()
if choice == '1':
add_question()
elif choice == '2':
attempt_test()
elif choice == '3':
list_questions()
elif choice == '4':
print("Exiting the application. Goodbye!")
break
else:
print("Invalid choice. Please select a valid option.\n")
if __name__ == "__main__":
main_menu()
Setup:
mcq_test.py.questions.json (if it exists) are in the same directory.Run the Program:
mcq_test.py.python mcq_test.py
Main Menu Options:
questions.json file.Adding a Question:
=== MCQ Test Application ===
1. Add a Question
2. Attempt Test
3. List All Questions
4. Exit
Select an option (1-4): 1
--- Add a New Question ---
Enter the question: What is the largest planet in our Solar System?
Enter option 1: Earth
Enter option 2: Jupiter
Enter option 3: Mars
Enter option 4: Saturn
Enter the correct answer: Jupiter
Question added successfully!
Attempting the Test:
=== MCQ Test Application ===
1. Add a Question
2. Attempt Test
3. List All Questions
4. Exit
Select an option (1-4): 2
--- Attempt the Test ---
Question 1: What is the largest planet in our Solar System?
1. Earth
2. Jupiter
3. Mars
4. Saturn
Your answer (enter the option number): 2
Correct!
Test Completed! Your score: 1/1
Data Handling:
load_questions function reads the questions.json file and loads the questions into a list. If the file doesn't exist or is empty, it returns an empty list.save_questions function writes the list of questions back to the questions.json file with proper indentation for readability.Adding Questions:
add_question function prompts the user to input the question text, four options, and the correct answer. It ensures that the correct answer is one of the provided options before saving.Attempting the Test:
attempt_test function iterates through each question, displays it with its options, and prompts the user to select an answer by entering the option number.Listing Questions:
list_questions function is an optional feature that allows users to view all the questions currently stored in the questions.json file.Main Menu:
main_menu function provides a simple textual interface for users to navigate between adding questions, attempting the test, listing questions, or exiting the application.This Python script provides a foundational way to manage and attempt MCQ tests using a JSON file for storage. It's simple, easy to use, and can be extended with additional features as needed. If you have any specific requirements or need further customization, feel free to ask!
Not yet included in a published release.