代码:
import json
import random
questions = json.load(open("questions.json"))
question = random.choice(questions.keys())
answers = questions[question]['answers']
correct_answer = questions[question]['correct_answer']
print question
for n, answer in enumerate(answers):
print "%d) %s" % (n + 1, answer)
resp = raw_input('answer: ')
if resp == str(correct_answer):
print "correct!"
else:
print "sorry, the correct answer was %s" % correct_answer
question.json:
{
"What are your plans for today?": {
"answers": ["nothing", "something", "do not know"],
"correct_answer": 2
},
"how are you?": {
"answers": ["well", "badly", "do not know"],
"correct_answer": 1
}
}
我想知道如何让这个程序继续提问,即使答案是对还是错,比如继续提问,而不是停止。
答案 0 :(得分:1)
以随机顺序询问所有问题,您可以使用random.shuffle
并通过for
循环询问所有问题。
import json
import random
# use items to get a list
questions = json.load(open("questions.json")).items()
# ... that you can shuffle.
random.shuffle(questions)
# note, we used items() earlier, so we get a tuple.
# and we can ask all questions in random order.
for question, data in questions:
answers = data['answers']
correct_answer = data['correct_answer']
print question
for n, answer in enumerate(answers):
print "%d) %s" % (n + 1, answer)
resp = raw_input('answer: ')
if resp == str(correct_answer):
print "correct!"
else:
print "sorry, the correct answer was %s" % correct_answer