<p>正如@Cixate所提到的,可以通过设置<code>correctAnswers = 0</code><strong>内部</strong><code>getVerb</code>并用while循环替换递归来解决这个问题:</p>
<pre><code>def getVerb():
correctAnswers = 0
... the rest of your code, as before ...
... making sure to replace the recursion with a while-loop ...
</code></pre>
<p><strong>问题是Python实际上看到两个不同的变量</strong>,在两个不同的范围内,<strong>具有相同的名称</strong>。这会导致所谓的“阴影”发生。在</p>
<p>因此,Python只在<code>getVerb</code>内部使用<code>getVerb</code>的{<cd5>}版本。而且这个变量从未被赋予值!所以Python抱怨说您试图在没有分配它的情况下使用它。在</p>
<p>但是。。。等待!我们没有赋值吗?好吧,我们分配了一个名为<code>correctAnswers</code>的变量,但它是一个不同的</strong>变量,具有不同的范围。在</p>
<p><strong>查看以下示例:</strong></p>
^{pr2}$
<p>所以,总结一下这种疯狂:</p>
<ul>
<li><code>y1</code>看到来自外部作用域的<code>x</code>——在第一行声明</li>
<li><code>y2</code><strong>创建自己的<code>x</code></strong>——不能看到或使用另一个</li>
<li>不管<code>y2</code>给它自己的<code>x</code></strong>分配了一个新值,外部的{<cd9>}仍然没有变化——请参见<code>outer 3</code>和{<cd16>}</li>
<li><code>y3</code>还创建了自己的<code>x</code>,但在它有值之前尝试使用它->;崩溃并烧录!!在</li>
</ul>
<hr/>
<p>做这一个改变将使你的程序工作。尽管这不是立即需要的,但您最终可能希望改进代码质量,并学习如何编写更地道的Python代码。例如:</p>
<ul>
<li>用while循环替换递归</li>
<li>使用字典</li>
<li>{{cd19>代替<cd20}</li>
</ul>
<p>但是,如果你继续保持良好的工作,这将随着时间和经验的自然到来!在</p>