Building a Quiz Program with a Text File: A Simple Guide
Have you ever wanted to create a fun and interactive quiz, but felt overwhelmed by the technicalities? This article guides you through building a simple quiz program using a text file, making it accessible for anyone with basic programming knowledge.
Scenario:
Let's imagine we want to create a "General Knowledge" quiz. We'll store the quiz questions and answers in a text file, and then use a Python script to read the file, ask the questions, and evaluate the user's responses.
Original Code:
def load_questions(filename):
"""Loads questions from a text file."""
questions = []
with open(filename, 'r') as file:
for line in file:
question, answer = line.strip().split("|")
questions.append((question, answer))
return questions
def quiz(questions):
"""Conducts the quiz."""
score = 0
for question, answer in questions:
print(question)
user_answer = input("Your answer: ")
if user_answer.lower() == answer.lower():
print("Correct!")
score += 1
else:
print(f"Incorrect. The correct answer was: {answer}")
print(f"\nYou scored {score} out of {len(questions)}.")
if __name__ == "__main__":
questions = load_questions("questions.txt")
quiz(questions)
Explanation:
-
load_questions(filename)
: This function takes the filename as input and opens it in read mode. It iterates through each line in the file, assuming that questions and answers are separated by a "|". The function splits the line and appends the question and answer as a tuple to a list calledquestions
, which is then returned. -
quiz(questions)
: This function takes the list of questions as input. It initializes the score to 0 and then iterates through each question in thequestions
list. For each question, it asks the user for their answer, compares the user's answer to the correct answer (ignoring case), and updates the score accordingly. Finally, it prints the user's score. -
if __name__ == "__main__":
: This part of the code ensures that theload_questions
andquiz
functions are only executed when the script is run directly, not when imported as a module.
Text File Structure:
The text file questions.txt
would look like this:
What is the capital of France?|Paris
What is the highest mountain in the world?|Mount Everest
What is the smallest country in the world?|Vatican City
Unique Insights:
- Flexibility: This approach is highly flexible. You can easily add or modify questions in the text file without needing to change the Python code.
- Scalability: You can create quizzes with many questions by simply adding more lines to the text file.
- Customization: You can easily modify the code to include different types of questions (multiple choice, true/false, etc.), or even add features like timer limits or scoring systems.
Further Enhancements:
- Error Handling: Add checks to ensure the file exists and has the correct format.
- User Interface: Use libraries like
Tkinter
orPyQt
to create a graphical user interface for a more visually appealing experience. - Database Integration: Store your quiz data in a database for easier management and scalability.
Conclusion:
Creating a quiz program using a text file is a great way to learn the basics of file handling and program logic. With this simple framework, you can build fun and interactive quizzes for various subjects. Remember, the possibilities are endless – unleash your creativity and start quizzing!
References: