<p>考虑以下方法:</p>
<ul>
<li>我们定义一个问答对列表。我们在一个地方这样做,所以它很容易维护,我们不必搜索整个文件进行更改或重复使用此代码为不同的问题集。你知道吗</li>
<li>我们创建了一个<code>ask_question</code>函数,我们可以调用它来处理所有的问题。这样,如果我们想改变我们如何实现我们的问题逻辑,我们只需要在一个地方(而不是在每个<code>questionXX</code>函数中)。你知道吗</li>
<li>我们使用<code>==</code>和非<code>in</code>比较用户输入和答案(<code>in</code>将做其他事情,而不是你所期望的)。你知道吗</li>
<li>我们创建一个对象来跟踪我们的答案结果。在这里,它是<code>ResultsStore</code>的一个实例,但是它可以是任何东西,让我们试着远离全局变量。你知道吗</li>
<li>提示回答时使用循环。如果给出的答案不正确(如果<code>retry_on_fail is False</code>),循环将重复。你知道吗</li>
<li>允许用户输入一些“skip”关键字来跳过问题。你知道吗</li>
<li>“测试”完成后显示结果。在这里,我们通过定义和调用<code>store.display_results()</code>方法来实现这一点。你知道吗</li>
</ul>
<p>那么,关于:</p>
<pre><code>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()
</code></pre>
<p>现在,返回值目前不起任何作用,但它可以!你知道吗</p>
<pre><code>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])
</code></pre>