title: Global variables in functions
body: <p>This works fine:</p>
  
  <pre><code>    import time
  
      def load():
          a = 0
          l = range(10000000)
          b = 100/len(l)
          start = time.time()
          for i in l:
              a += b
          end = time.time()
          print(end-start)
  
      load()
  </code></pre>
  
  <p>Now I want my function to use <code>a</code> as a global variable:</p>
  
  <pre><code>import time
  
  a = 0
  
  def f():
      global a
      a = 0
  
  def load():
      l = range(10000000)
      b = 100/len(l)
      start = time.time()
      for i in l:
          a += b
      end = time.time()
      print(end-start)
  f()
  load()
  </code></pre>
  
  <p>But it returns an Error: <code>UnboundLocalError: local variable 'a' referenced before assignment</code></p>
  
  <p>Edit:</p>
  
  <p>I found this in a thread and it works:</p>
  
  <pre><code>globvar = 0
  
  def set_globvar_to_one():
      global globvar    # Needed to modify global copy of globvar
  
  def print_globvar():
      print(globvar)     # No need for global declaration to read value of globvar
  
  set_globvar_to_one()
  print_globvar()       # Prints 1
  </code></pre>
  
  <p>But what is the difference to my function?</p>