title: Python - How to reference a global variable from a function
body: <p>I must be missing some very basic concept about Python's variable's scopes, but I couldn't figure out what.</p>
  
  <p>I'm writing a simple script in which I would like to access a variable that is declared outside the scope of the function : </p>
  
  <pre><code>counter = 0
  
  def howManyTimesAmICalled():
      counter += 1
      print(counter)
  
  howManyTimesAmICalled()
  </code></pre>
  
  <p>Unexpectedly for me, when running I get :</p>
  
  <pre><code>UnboundLocalError: local variable 'counter' referenced before assignment
  </code></pre>
  
  <p>Adding a global declaration at the first line </p>
  
  <pre><code>global counter
  def howManyTimesAmICalled():
      counter += 1
      print(counter)
  
  howManyTimesAmICalled() 
  </code></pre>
  
  <p>did not change the error message.</p>
  
  <p>What am I doing wrong? What is the right way to do it?</p>
  
  <p>Thanks!</p>