2013-02-08 79 views
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 

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

我想知道我怎樣才能使這個方案繼續問問題,即使答案是正確的或者錯誤,就像繼續提問一樣,而不會阻止它。

回答

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 
+0

正是我想要的。 tanksss – 2013-02-08 20:35:04