Python 连续问题

Python 连续问题,python,Python,代码: 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

代码:

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
{
  "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
  }
}
question.json:

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
{
  "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
  }
}

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

要以随机顺序提问所有问题,可以使用
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

正是我想要的。坦克