title: Why do I get a NameError: name 'counter' is not defined, while I set the counter variable to global?
body: <p>Below is my code.  I don't know what I am doing wrong, but when I run this, I get NameError: name 'counter' is not defined. I'm learning Python from a textbook and according to the textbook my code is right. I can't find the difference between the textbook code and this code... I've seen other questions on stackoverflow about global variables, but I still can't figure out what I did wrong. Why do I get this error? And how to solve it?</p>
  
  <p>UPDATE:
  I know what I did wrong. I should write counter = 0 above the function.</p>
  
  <pre><code>def rpower(a, n):
      'returns a to the nth power'
      global counter          # counts number of multiplications
  
      if n == 0:
          return 1
      # if n &gt; 0:
      tmp = rpower(a, n//2)
  
      if n%2 == 0:
          counter += 1
          return tmp*tmp      # 1 multiplication
  
      else:
          counter += 2
          return a*tmp*tmp    # 2 multiplications
  
  print(rpower(2, 10000))
  </code></pre>