title: Error when referencing a inside a function without using `global` keyword in python
body: <p>Why does the following code raise an <code>UnboundedLocalError</code>:</p>
  <pre class="lang-py prettyprint-override"><code>n = 0
  def foo():
      n = n + 1
      print(n)
  foo()
  foo()
  </code></pre>
  <p>Error:</p>
  <pre><code>Traceback (most recent call last):
    File &quot;foo.py&quot;, line 5, in &lt;module&gt;
      foo()
    File &quot;foo.py&quot;, line 3, in foo
      n = n + 1
  UnboundLocalError: local variable 'n' referenced before assignment
  </code></pre>
  <p>While the following code works:</p>
  <pre class="lang-py prettyprint-override"><code>n = 0
  def foo():
      print(n)
  foo()
  foo()
  </code></pre>
  <p>Output:</p>
  <pre><code>0
  0
  </code></pre>
  <p>It seems to me that given the behavior of the second snippet, the first snippet should use the value of the <em>global</em> <code>n</code> to calculate <code>n+1</code> and assign it to a new <em>local</em> <code>n</code>, and print it. Thus, I would expect the output to be two <code>1</code>s. Why does this not happen?</p>