Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/289.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python类Flashcard在循环中测试用户_Python_Class_Loops - Fatal编程技术网

Python类Flashcard在循环中测试用户

Python类Flashcard在循环中测试用户,python,class,loops,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 qui

我正在尝试创建一个循环,用我创建的抽认卡测试用户。当用户想要退出时,他们应该能够键入字母“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()

当我运行代码时,我得到一个错误,表示“赋值前引用的局部变量‘不正确’”。我如何记录正确答案和错误答案?我应该在quick_user()中返回的不仅仅是True和False吗?在一个新类中进行测验循环会有帮助吗?

是的,您需要先声明两个变量,然后每次将它们传入并取出,因此请尝试以下方法:

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
这应该允许您继续使用真假结构,并让代码正常工作。然后,您还可以去掉类中对correct和error的引用,并将print语句放入while循环中。还要改变这一点:

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

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

在输入q时停止程序。

在我切换正确和不正确的建议后,这项功能起到了作用。当用户输入“q”时,您对如何使程序停止运行有何想法?现在它似乎永远在循环。更改答案以修复正确和错误的按钮问题,并添加在输入q时结束循环的功能。你需要把我修改过的两段代码都放进去才能工作。工作得很好,只是在我输入q时无法结束程序,直到我将“else:break”改为“elif result==None:break”本不应该有什么不同,但我很高兴它对你一直有效。