UnboundLocalError: local variable 'sum' referenced before assignment
<p>Code1:</p>

<pre class="lang-py prettyprint-override"><code># coding:utf-8

sum = 5

def add(x, y):
    print sum
    sum = x + y

if __name__ == '__main__':
    add(7, 8)
</code></pre>

<p>When I run the code above, I got the following error:</p>

<pre><code>ssspure:python ssspure$ python test.py
Traceback (most recent call last):
  File "test.py", line 11, in &lt;module&gt;
    add(7, 8)
  File "test.py", line 6, in add
    print sum
UnboundLocalError: local variable 'sum' referenced before assignment
</code></pre>

<p>Code2:</p>

<pre class="lang-py prettyprint-override"><code># coding:utf-8

sum = 5

def add(x, y):
    sum = x + y
    print sum

if __name__ == '__main__':
    add(7, 8)
</code></pre>

<p>I can run code2 successfully.</p>

<p>I only moved the <code>print sum</code> below "sum = x + y" statement. Why did Code1 fail but Code2 runs successfully?</p>