0

代码:

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

问题.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
  }
}

我想知道如何让这个程序继续提问,即使答案是对还是错,就像做持续的问题一样,而不停止它。

4

1 回答 1

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
于 2013-02-08T17:53:59.657 回答