title: Pygame local variable referenced before assignment
body: <p>I want to make a rectangle to run using keys but I take an error on line 34:</p>
  
  <pre><code>UnboundLocalError: local variable 'x' referenced before assignment
  </code></pre>
  
  <p>I can't fix that. Please help me.</p>
  
  <p>Here is my code:</p>
  
  <pre><code>import pygame
  import sys
  from pygame.locals import *
  
  fps = 30
  fpsclock = pygame.time.Clock()
  w = 640
  h = 420
  blue = (0, 0, 255)
  white = (255, 255, 255)
  x = w / 3
  y = 350
  boxa = 20
  movex = 0
  
  
  def drawwindow():
      global screen
      pygame.init()
      screen = pygame.display.set_mode((w, h))
      screen.fill(blue)
  
  
  def drawbox(box):
      if box.right &gt; (w - boxa):
          box.right = (w - boxa)
      if box.left &lt; 0:
          box.left = 0
      pygame.draw.rect(screen, white, box)
  
  
  def main():
      drawwindow()
      box1 = pygame.Rect(x, y, boxa, boxa)
      drawbox(box1)
  
      while True:
          for event in pygame.event.get():
              if event.type == QUIT:
                  pygame.quit()
                  sys.exit()
              if event.type == KEYDOWN:
                  if event.key == K_RIGHT:
                      movex = +4
                  if event.key == K_LEFT:
                      movex = -4
              if event.type == KEYUP:
                  if event.key == K_RIGHT:
                      movex = 0
                  if event.key == K_LEFT:
                      movex = 0
          x += movex
          pygame.display.update()
          fpsclock.tick(fps)
  
  if __name__ == '__main__':
      main()
  </code></pre>