<p>借用<a href="https://stackoverflow.com/questions/291978/short-description-of-python-scoping-rules">Short Description of the Scoping Rules?</a>Python的作用域规则非常容易记住:</p>
<ul>
<li><strong>L</strong>ocal任何局部范围;例如:函数</li>
<li><strong>E</strong>封闭任何封闭范围,例如:<code>def g():</code>内<code>def f()</code></li>
<li><strong>G</strong>lobal任何声明的“globals”,例如:<code>global x</code></li>
<li><strong>B</strong>u在任何内置函数中,`。例如:<code>max()</code></li>
</ul>
<p>在示例代码中:(<em>假设函数</em>)</p>
<pre><code>def foo():
num = int(input("Type a number: ")) # ^
while (num != 9999): # |
add = 0 # |
counter = 0 # |
while (num != 0): # |
add = add + num # |
counter += 1 # LOCAL
num = int(input("Type another value: ")) # |
print(round(soma/contador,3)) # |
num = int( # |
input(( # |
"Next sequence of values. " # |
"Type a number: " # |
)) # |
) # V
</code></pre>