2016-08-03 161 views
0

最近,我一直在試圖編寫一個程序,它會向用戶提問,然後檢查答案。但有一個問題:更改變量不影響while循環

get_questions=["What color is the daytime sky on a clear day? ", "blue", 
       "What is the answer to life, the universe and everything? ", "42", 
       "What is a three letter word for mouse trap? ", "cat", 
       "What noise does a truly advanced machine make?","ping"] 
total=0 
total2=0 
good=0 
def give_questions(): 
    global get_questions 
    global total2 
    global total 
    global good 
    add1=0 
    add2=1 
    question=get_questions[add1] 
    answer=get_questions[add2] 
    print 
    while total != 4: 
     print question 
     print 
     answer_given=raw_input("Answer: ") 
     if answer_given != answer: 
       print 
       print "Wrong. The correct answer was",answer,"." 
       print 
       total2=total2+1 
       total=total+1 
       add1=add1+2 
       add2=add2+2 
     else: 
       print 
       print "Correct" 
       print 
       total2=total2+1 
       total=total+1 
       good=good+1 
       add1=add1+2 
       add2=add2+2 
give_questions() 

每當我運行此,奇怪的是同樣的問題,並回答一次又一次運行,直到變量total已經達到了4.當我在if語句寫道:print add2,從1去如預期的那樣,3至5。但問題或答案不會改變。

回答

0

你永遠不會更新你的問題和答案,因爲它們在'while'循環之外。因此,通過你的循環,它會一直問你同樣的問題。下面是一個question = get_questions[add1]answer = get_questions[add2]的示例代碼的while環路內移動:

get_questions = ["What color is the daytime sky on a clear day? ", "blue", 
       "What is the answer to life, the universe and everything? ", "42", 
       "What is a three letter word for mouse trap? ", "cat", 
       "What noise does a truly advanced machine make?", "ping"] 
total = 0 
total2 = 0 
good = 0 

def give_questions(): 
    global get_questions 
    global total 
    global total2 
    global good 
    add1 = 0 
    add2 = 1 

    while total != 4: 
     question = get_questions[add1] 
     answer = get_questions[add2] 

     print(question) 
     answer_given = input("Answer:") 
     if answer_given != answer: 
      print ("Wrong. The correct answer was" ,answer) 
      total2 += 1 
      total += 1 
      add1 += 2 
      add2 += 2 

     else: 
      print ("Correct") 
      total2 += 1 
      total += 1 
      good += 1 
      add1 += 2 
      add2 += 2 

give_questions() 

注:似乎有很多在你的代碼不必要的「打印」語句不出現做任何事情的。爲了簡化它,我從上面的代碼中刪除了它們。

+0

謝謝馬克。你救了我很多麻煩。 –

+0

如果這解決了您的問題,請接受答案。 – DavidG