擅长:python、mysql、java
<p>有两种方法可以实现相同的目的:</p>
<p><strong>使用参数并返回(推荐)</strong></p>
<pre><code>def other_function(parameter):
return parameter + 5
def main_function():
x = 10
print x
x = other_function(x)
print x
</code></pre>
<p>运行<code>main_function</code>时,将得到以下输出</p>
<pre><code>>>> 10
>>> 15
</code></pre>
<p><strong>使用全局变量(切勿执行此操作)</strong></p>
<pre><code>x = 0 # The initial value of x, with global scope
def other_function():
global x
x = x + 5
def main_function():
print x # Just printing - no need to declare global yet
global x # So we can change the global x
x = 10
print x
other_function()
print x
</code></pre>
<p>现在你将得到:</p>
<pre><code>>>> 0 # Initial global value
>>> 10 # Now we've set it to 10 in `main_function()`
>>> 15 # Now we've added 5 in `other_function()`
</code></pre>