自限重函数

2024-03-29 14:19:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在为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()

好吧,这样就行了,但是对每个“enterbox”问题使用嵌套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()  

它是这样工作的,所以从什么提供的任何错误可能是我的错误,从复制和粘贴。 如果有帮助的话,我还在python2.7rc1中运行它。 谢谢你的帮助。你知道吗

我不知道是否有一种方法,结合“enterbox”有一个按钮“跳过”,因为这也将是一个解决方案。你知道吗


Tags: of方法inaddiftitleisversion
2条回答

考虑以下方法:

  • 我们定义一个问答对列表。我们在一个地方这样做,所以它很容易维护,我们不必搜索整个文件进行更改或重复使用此代码为不同的问题集。你知道吗
  • 我们创建了一个ask_question函数,我们可以调用它来处理所有的问题。这样,如果我们想改变我们如何实现我们的问题逻辑,我们只需要在一个地方(而不是在每个questionXX函数中)。你知道吗
  • 我们使用==和非in比较用户输入和答案(in将做其他事情,而不是你所期望的)。你知道吗
  • 我们创建一个对象来跟踪我们的答案结果。在这里,它是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])

快速而肮脏的解决方案可以使用默认值“skip”作为答案:

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() 

但你真的应该研究犹太矮人给出的答案。有很多东西要学 程序设计。他不是给你鱼,他是教你钓鱼。你知道吗

相关问题 更多 >