Reputation: 11
I'm trying to make a quiz in Python. I have found many tutorials that print the questions using print("question") but I think that would take a lot of time to write. I have all of my questions saved in a text document. Can't I make a list and import the questions from the document? Like infile = "questions.txt", "r")
I know this works for simple lists like (apple, orange, banana) but if the question is multi-lined, like for a multiple choice questions, how does that work in a list?
Also, I figured I could have a separate list of the answers, so that question[2] would match up with answer[2] etc. That list is easy since they are single letters.
Any help and advice would be appreciated! Thanks!
Upvotes: 1
Views: 4126
Reputation: 46759
You could store all of your questions and answers in a text file using the following format. Each line in the file could contain one question, one correct answer and a list of possible answers. For example:
What is 1+1 2 2 4 6 8
Subtract 5 from 25, what do you get 20 10 30 25 20 12
So for the first line you have the question, the answer of 2
, and four possible answers.
After each part add a tab
character. It is then possible to use Python's CSV library to read each question into a list. From this list you could randomly select one of the quiz questions as follows:
import csv, random
with open("questions.csv", "r") as f_input:
csv_input = csv.reader(f_input, delimiter="\t")
quiz = list(csv_input)
while True:
# Choose a random question from the quiz
question = random.choice(quiz)
print "%s?" % (question[0])
while True:
# Display the possible answers with commas and 'or' at the end.
print "Is the answer: %s or %s?" % (", ".join(question[2:-1]), question[-1])
user_answer = raw_input()
# Did the user select a valid choice?
if user_answer in question[2:]:
break
# Stop asking questions?
if len(user_answer) == 0:
print "Good bye"
break
if user_answer == question[1]:
print "Correct"
else:
print "Incorrect"
print
This script would read all of your questions and answers into a single list called quiz
. The first entry in quiz would look like:
['What is 1+1', '2', '2', '4', '6', '9']
The first part is the question, the second the correct answer, and the remaining entries are as many possible answers as you would like to offer. If the user just presses enter, the quiz will finish.
Hopefully this helps.
Tested using Python 2.7
Upvotes: 0
Reputation: 304137
A simple way is to create your file with an extra blank line between the questions.
with open("questions.txt", "rU") as infile:
questions = infile.read().split("\n\n")
Upvotes: 2