自我限制功能

时间:2018-06-16 07:58:12

标签: python function limit repeat

我正在为我的A& P课程的当前部分编写一个基本上是学习指南/练习测试的程序(这让我更加投入,而不仅仅是重复阅读笔记)。测试没有任何问题,但我有一个问题,我的一些问题使用" enterbox"输入,如果答案不正确,我可以有问题循环,但如果没有正确的答案,我无法解决问题。 我找到了一种方法,通过将整个功能放回到最初的" else"树,这是对或错你进入下一个问题,但它看起来非常难看,我不能相信没有更好的方法。 所以我的解决方案"看起来像这样:

def question82():
   x = "which type of metabolism provides the maximum amount of ATP needed for contraction?"
   ques82 = enterbox(msg = x, title = version)
   #version is a variable defined earlier
   if ques82.lower() in ["aerobic"]:
        add() #a function that is explained in the example further below
        question83()
   else:
        loss() #again its a housecleaning function shown below
        ques82b = enterbox(msg = x, title = version)
        if ques82b.lower() in ["aerobic"]:
            add()
            question83()
        else:
            loss()
            question83()

好的,所以它有效,但是为每个"输入框"使用嵌套的if树。问题看起来有点草率。我自学成才,这可能是唯一的解决方案,但如果有更好的东西,我很乐意了解它。

所以这是我的计划的完整部分:

from easygui import * 
import sys

version = 'A&P EXAM 3 REVIEW'
points = 0

def add():
    global points
    msgbox("Correct", title = version)
    points = points + 1

def loss():
    global points
    msgbox("Try Again", title = version)
    points = points - 1  

def question81():
    x = "What chemical is stored by muscle as a source of readily available energy for muscle contractions"
    ques81 = enterbox(msg = x, title = version)
    if ques81.lower() in ["creatine"]:
        add()
        question82()
    else:
        loss()
        question81()  

它的工作原理如此,所提供的任何错误都可能是我的复制和粘贴错误。 我也在python 2.7rc1中运行它,如果这有帮助的话。 感谢您提前提供任何帮助。

我不知道是否有办法合并" enterbox"它有一个按钮,用于"跳过"因为那也是一个解决方案。

2 个答案:

答案 0 :(得分:3)

考虑以下方法:

  • 我们定义问答对列表。我们在一个地方这样做,因此它很容易维护,我们不必搜索整个文件来进行更改或重复使用此代码来处理不同的问题集。
  • 我们创建了一个ask_question函数,我们可以调用所有的问题。这样,如果我们想要改变我们如何实现我们的问题逻辑,我们只需要在一个位置(而不是每个questionXX函数中)。
  • 我们使用==将用户输入与我们的答案进行比较而不是inin会做其他事情,而不是您期望的事情。)
  • 我们创建一个对象来跟踪我们的答案结果。在这里,它是ResultsStore的一个实例,但它可以是任何真实的东西,让我们试着摆脱全局变量。
  • 提示答案时使用循环。如果给出的答案不正确(如果retry_on_fail is False),则循环将重复。
  • 允许用户输入一些“skip”关键字以跳过问题。
  • “测试”完成后显示结果。在这里,我们通过定义和调用store.display_results()方法来实现这一点。

那么,那么:

from easygui import enterbox

question_answer_pairs = [
    ("1 + 1 = ?", "2"),
    ("2 * 3 = ?", "6"),
    ("which type of metabolism provides the maximum amount of ATP needed for contraction?", "aerobic")
]

VERSION = 'A&P EXAM 3 REVIEW'

class ResultStore:
    def __init__(self):
        self.num_correct = 0
        self.num_skipped = 0
        self.num_wrong = 0

    def show_results(self):
        print("Results:")
        print("  Correct:", self.num_correct)
        print("  Skipped:", self.num_skipped)
        print("  Wrong:  ", self.num_wrong)


def ask_question(q, a, rs, retry_on_fail=True):
    while True:
        resp = enterbox(msg=q, title=VERSION)
        # Force resp to be a string if nothing is entered (so .lower() doesn't throw)
        if resp is None: resp = ''
        if resp.lower() == a.lower():
            rs.num_correct += 1
            return True
        if resp.lower() == "skip":
            rs.num_skipped += 1
            return None

        # If we get here, we haven't returned (so the answer was neither correct nor
        #   "skip").  Increment num_wrong and check whether we should repeat.
        rs.num_wrong += 1
        if retry_on_fail is False:
            return False

# Create a ResultsStore object to keep track of how we did
store = ResultStore()

# Ask questions
for (q,a) in question_answer_pairs:
    ask_question(q, a, store)

# Display results (calling the .show_results() method on the ResultsStore object)
store.show_results()

现在,返回值当前没有做任何事情,但它可以!

RES_MAP = {
    True: "Correct!",
    None: "(skipped)",
    False: "Incorrect"          # Will only be shown if retry_on_fail is False
}

for (q,a) in question_answer_pairs:
    res = ask_question(q, a, store)
    print(RES_MAP[res])

答案 1 :(得分:0)

快速而肮脏的解决方案可以使用默认值"跳过"答案:

def question81():
x = "What chemical is stored by muscle as a source of readily available energy for muscle contractions"
ques81 = enterbox(msg = x, title = version, default = "skip")
if ques81.lower() == 'creatine':
    add()
    question82()
elif ques81 == 'skip':
    # Do something
else:
    loss()
    question81() 

但你应该真正研究jedwards给出的答案。有很多值得学习的地方 程序设计。他没有给你鱼,他教你钓鱼。