title: Unbound Local Error with global variable
body: <p>I am trying to figure out why I get an UnboundLocalError in my pygame application, Table Wars. Here is a summary of what happens:</p>
  
  <p>The variables, <code>REDGOLD</code>, <code>REDCOMMAND</code>, <code>BLUEGOLD</code> and <code>BLUECOMMAND</code>, are initialised as global variables:</p>
  
  <pre><code>#Red Stat Section
  REDGOLD = 50
  REDCOMMAND = 100
  #Blue Stat Section
  BLUEGOLD = 50
  BLUECOMMAND = 100
  
  def main():    
  
      [...]
  
      global REDGOLD
      global REDCOMMAND
      global BLUEGOLD
      global BLUECOMMAND
  </code></pre>
  
  <p>This works when spawning units within the main loop, subtracting funds to spawn units.</p>
  
  <p>Right now, I am trying to set up a system so that when a unit dies, the killer refunds the victim's <code>COMMAND</code> and earns <code>GOLD</code> based on what he killed:</p>
  
  <pre><code>class Red_Infantry(pygame.sprite.Sprite):
  def __init__(self, screen):
      [...]
      self.reward = 15
      self.cmdback = 5
  
  [...]
  
  def attack(self):
      if self.target is None: return
      if self.target.health &lt;= 0:
          REDGOLD += self.target.reward          #These are the problem lines
          BLUECOMMAND += self.target.cmdback     #They will cause the UnboundLocalError
                                                 #when performed
          self.target = None
      if not self.cooldown_ready(): return
      self.target.health -= self.attack_damage
      print "Target's health: %d" % self.target.health
  </code></pre>
  
  <p>This works right up until the unit dies. Then this happens:</p>
  
  <pre><code>Traceback (most recent call last):
  File "C:\Users\Oventoaster\Desktop\Games\Table Wars\Table Wars.py", line 606, in &lt;module&gt;
  main()
  File "C:\Users\Oventoaster\Desktop\Games\Table Wars\Table Wars.py", line 123, in main
  RedTeam.update()
  File "C:\Python27\lib\site-packages\pygame\sprite.py", line 399, in update
  for s in self.sprites(): s.update(*args)
  File "C:\Users\Oventoaster\Desktop\Games\Table Wars\Table Wars.py", line 304, in update
  self.attack()
  File "C:\Users\Oventoaster\Desktop\Games\Table Wars\Table Wars.py", line 320, in attack
  REDGOLD += self.target.reward
  UnboundLocalError: local variable 'REDGOLD' referenced before assignment
  </code></pre>
  
  <p>How do I get the global variables mentioned above to change with the <code>attack</code> block? If it helps, I am using Pygame 2.7.x, so <code>nonlocal</code> won't work :/</p>