2014-12-02 46 views
-4

我想編寫一個程序,詢問用戶問題,然後檢查他的答案。這裏顯示3個問題和3個答案。我能夠爲單個問題 - 答案對編寫它,但是對於所有對使用同一段代碼時遇到困難 - 我不想爲每個問題 - 答案對使用顯式代碼,因爲它會產生很多code.I將不勝感激幫助使它適用於所有問題。循環變量和測試用戶輸入

Q1 = "Question 1 Is 30 fps more cinematic than 60 fps? - a)Yes, b)No, c)It's a matter of opinion or d)Nobody knows" 
A1 = "b" 
Q2 = "Question 2 Test Question? - a), b), c) or d)" 
A2 = "b" 
Q3 = "Question 3 If 10 + 9 is 19 what is 9 + 10? - a)19, b)20, c)21 or d)22" 
A3 = "c"  
def quiz(): 
    n = 0 
    while n < 3: 
     n = n + 1 

    if str(input(Q1)) == A1: 
     print("Correct answer") 
    else: 
     print("Wrong Answer, Correct Answer is", A1) 

print(quiz()) 
+0

使用數據庫? – 2014-12-02 15:08:18

回答

1

使用列表來保存您的問題和答案,並zip迭代兩者。

qus = [Q1, Q2, Q3, ...] 
ans = [A1, A2, A3, ...] 

def quiz(): 
    for q, a in zip(qus, ans): 
     if str(input(q)) == a: 
      print ("Correct answer") 
     else: 
      print("Wrong Answer, Correct Answer is", a) 
quiz() 
1

你可以用類似的數據結構來做到這一點。這也將處理不同的問題風格。

questions = [{"question": "Is 30 fps more cinematic than 60 fps?", 
       "answers": {"a": "Yes", 
          "b": "No", 
          "c": "It's a matter of opinion", 
          "d": "Nobody knows"}, 
       "correct": "b"}, 
      {"question": "Question 2 Test Question?", 
       "answers": {"a": "", 
          "b": "", 
          "c": "", 
          "d": ""}, 
       "correct": "b"}, 
      {"question": "Question 3 If 10 + 9 is 19 what is 9 + 10?", 
       "answers": {"a": "19", 
          "b": "20", 
          "c": "21", 
          "d": "22"}, 
       "correct": "c"}, 
      ] 
def quiz(): 
    for question in questions: 
     print(question["question"]) 
     for choice, answer in question["answers"].iteritems(): 
      print("{:s}: {:s}".format(choice, answer)) 

     if str(input()) == question["correct"]: 
      print("Correct answer") 
     else: 
      print("Wrong Answer, Correct Answer is", question["correct"]) 
quiz()