2016-07-26 113 views
-3

我想要我現在必須通過一個無限的問題列表,或直到有人得到一個答案錯誤的代碼。我目前使用的是連續的隨機問題?

random.shuffle(questions) 

for question in questions: 
    question.ask() 

要求列表中的每一個問題都需要一次。

如何在用戶輸入錯誤答案之前持續詢問?這是我目前的代碼:

class Question(object): 
    def __init__(self, question, answer): 
     self.question = question 
     self.answer = answer 

    def ask(self): 

     response = input(self.question) 
     if response == self.answer: 
      print "CORRECT" 
     else: 
      print "wrong" 

questions = [ 
    Question("0", 0), 
    Question("π/6", 30), 
    Question("π/3", 60), 
    Question("π/4", 45), 
    Question("π/2", 90), 
    Question("2π/3", 120), 
    Question("3π/4", 135), 
    Question("5π/6", 150), 
    Question("π", 180), 
    Question("7π/6", 210), 
    Question("4π/3", 240), 
    Question("5π/4", 225), 
    Question("3π/2", 270), 
    Question("5π/3", 300), 
    Question("7π/4", 315), 
    Question("11π/6", 330), 
    Question("2π",360), 
] 

此外,如果你能告訴我如何爲每個問題添加一個分數正確的,將不勝感激。我試圖這樣做,但我已經有一段程序每5秒鐘從一個全局評分變量中扣除1。我想繼續編輯相同的變量,但它會給出錯誤。

+0

這真的是你的縮進嗎? – Li357

+2

[Python 3.4.3中的循環]的可能重複或任何數量的「不斷詢問用戶,直到___」的問題[1](http://stackoverflow.com/questions/20337489/python-how-to-keep-repeating-a-program-until-a-specific-input-is-obtained),[2](http:/ /stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response),[3](http://stackoverflow.com/questions/8114355/loop-直到特定用戶輸入),[4](http://stackoverflow.com/questions/12556907/continually-prompting-user-for-input-in-python)等 – TessellatingHeckler

+0

哦,我的壞,它似乎已經搞亂了,當我複製,我會修復 – Warstolrem

回答

0

這可能是值得一試給問()返回值。如果答案正確,則爲真;如果答案不正確,則爲假。這可能是這樣的:
(!你會首先必須創建一個分數變量)

for q in questions: 
    if q.ask() is True: 
     score += 1 
    else: 
     break #Breaks out of the while loop 

Eitherway,你必須:

def ask(self): 
    response = input(self.question) 
    if response == self.answer: 
     print "CORRECT" 
     return True 
    else: 
     print "wrong" 
     return False 

然後,你可以通過這樣的問題迭代讓你的答案爲了不把字符串與整數(它將永遠不會相同)進行比較,所以問題應該如下所示:

questions = [ 
    Question("0", "0"), 
    Question("π/6", "30"), 
    Question("π/3", "60"), 
    Question("π/4", "45"), 
    ... 

我希望我能幫助你!

0

你可以遍歷列表while循環這樣的事情可能

score = 0 
currIndex = 0 

#ask a question to start off 
q1 = questions[currIndex] 
#get the answer 
answer = q1.ask() 
while(answer == q1.answer): 
    #ask the question at this index 
    score+=1 
    q1=questions[currIndex] 
    answer = q1.ask() 

    currIndex+=1 
    #reset the loop? 
    if currIndex == len(questions)-1: 
     currIndex = 0 

沒有測試它尚未但這應該工作?它會一直持續下去,直到他們得到答案錯誤,否則無限。 編輯:哎呦沒讀過完全,我會做問返回正確或錯誤,則循環改變

while (answer == "CORRECT"):