Python - 类Flashcard - 在循环中测验用户

时间:2014-12-01 19:03:53

标签: python class loops

我正在尝试创建一个循环,用我创建的抽认卡来测验用户。当用户想要退出时,他们应该能够输入字母' q'并打印正确和错误答案的数量。这就是我所拥有的:

class Flashcard(object):
    def __init__(self, q, a) :
        self.question = q
        self.answer = a
    def print_question(self) :
        print self.question
    def quiz_user(self) :
        self.print_question()
        ans = raw_input("? ")
        correct = 0
        incorrect = 0
        if ans.strip().lower() == self.answer.strip().lower() and ans.strip().lower() != 'q':
            print "Good job!"
            correct = correct + 1
            return True
        elif ans.strip().lower() != self.answer.strip().lower() and ans.strip().lower() != 'q':
            print "Sorry, the answer was:", self.answer
            incorrect = incorrect + 1
            return False
        elif ans.strip().lower() == 'q':
            print "correct:", correct
            print "incorrect:", incorrect

import random

cards = [
    Flashcard("What is largest country in Africa?", "Algeria"),
    Flashcard("What is a group of larks called?", "exaltation")
    ]
while True :
    random.choice(cards).quiz_user()

当我运行代码时,我收到一条错误消息,指出"本地变量'不正确'在转让之前引用"。如何跟踪正确和错误的答案?我应该在quiz_user()中返回的不仅仅是True和False吗?是否有助于在新课程中进行测验循环?

1 个答案:

答案 0 :(得分:1)

是的,你需要首先声明这两个变量,然后将它们传递给每次都取出它们,所以试试这个:

correct = 0
incorrect = 0
cards = [
    Flashcard("What is largest country in Africa?", "Algeria"),
    Flashcard("What is a group of larks called?", "exaltation")
    ]
while True :
    result = random.choice(cards).quiz_user()
    if result: correct += 1
    elif not result: incorrect += 1
    else: break

这应该允许您继续使用您的True False结构,并让代码工作。您也可以在类中删除对正确和不正确的引用,并将print语句放在while循环中。也改变这个:

elif ans.strip().lower() == 'q':
    print "correct:", correct
    print "incorrect:", incorrect

到此:

elif ans.strip().lower() == 'q': return None

在输入q时停止程序。