title: Cannot Access Variable Outside of Function
body: <p>I keep getting the following error when trying to access a variable from one function inside another function.</p>
  
  <p>NameError: global name 'savemovieurl' is not defined</p>
  
  <p>how can i access the "savemovieurl" from the function "tmdb_posters" inside "dynamic_data_entry" to save it to the database?</p>
  
  <p>i've tried adding global to the variable name, and had no success.</p>
  
  <pre><code>import requests
  import urllib
  
  import sqlite3
  import time
  import datetime
  import random
  
  
  
  movie = raw_input('Enter your movie: ')
  print('You searched for: ', movie)
  
  def imdb_id_from_title(title):
      """ return IMDb movie id for search string
  
          Args::
              title (str): the movie title search string
          Returns: 
              str. IMDB id, e.g., 'tt0095016' 
              None. If no match was found
      """
      pattern = 'http://www.imdb.com/xml/find?json=1&amp;nr=1&amp;tt=on&amp;q={movie_title}'
      url = pattern.format(movie_title=urllib.quote(title))
      r = requests.get(url)
      res = r.json()
      # sections in descending order or preference
      for section in ['popular','exact','substring']:
          key = 'title_' + section 
          if key in res:
              return res[key][0]['id']
  
  if __name__=="__main__":
      title = movie
      imdb_info_returned = ("{1}".format(title, imdb_id_from_title(title)))
      print imdb_info_returned
  
  
  import os
  import requests
  
  CONFIG_PATTERN = 'http://api.themoviedb.org/3/configuration?api_key={key}'
  IMG_PATTERN = 'http://api.themoviedb.org/3/movie/{imdbid}/images?api_key={key}' 
  KEY = '47db65094c31430c5a2b65112088d70e'
  
  imdb_id_input = imdb_info_returned
  print('You searched for: ', imdb_id_input)
  
  
  
  def _get_json(url):
      r = requests.get(url)
      return r.json()
  
  def _download_images(urls, path='.'):
      """download all images in list 'urls' to 'path' """
  
      for nr, url in enumerate(urls):
          r = requests.get(url)
          filetype = r.headers['content-type'].split('/')[-1]
          filename = 'poster_{0}.{1}'.format(nr+1,filetype)
          filepath = os.path.join(path, filename)
          with open(filepath,'wb') as w:
              w.write(r.content)
  
  def get_poster_urls(imdbid):
      """ return image urls of posters for IMDB id
          returns all poster images from 'themoviedb.org'. Uses the
          maximum available size. 
          Args:
              imdbid (str): IMDB id of the movie
          Returns:
              list: list of urls to the images
      """
      config = _get_json(CONFIG_PATTERN.format(key=KEY))
      base_url = config['images']['base_url']
      sizes = config['images']['poster_sizes']
  
      """
          'sizes' should be sorted in ascending order, so
              max_size = sizes[-1]
          should get the largest size as well.        
      """
      def size_str_to_int(x):
          return float("inf") if x == 'original' else int(x[1:])
      max_size = max(sizes, key=size_str_to_int)
  
      posters = _get_json(IMG_PATTERN.format(key=KEY,imdbid=imdbid))['posters']
      poster_urls = []
  
  
      rel_path = posters[0]['file_path']
      url = "{0}{1}{2}".format(base_url, max_size, rel_path)
      poster_urls.append(url) 
  
      return poster_urls
  
  def tmdb_posters(imdbid, count=None, outpath='.'):    
      urls = get_poster_urls(imdbid)
      if count is not None:
          urls = urls[:count]
      _download_images(urls, outpath)
  
  
  
  
      savemovieurl = urls
      print savemovieurl
  
  
  
  
  
  conn = sqlite3.connect('tutorial.db')
  c = conn.cursor()
  
  
  
  def create_table():
      c.execute("CREATE TABLE IF NOT EXISTS movies(unix REAL, datestamp TEXT, keyword TEXT, value REAL, moviename TEXT, movieimage TEXT, movieurl TEXT)")
  
  def data_entry():
      c.execute("INSERT INTO movies VALUES(1452549219,'2016-01-11 13:53:39','Python',6,'movienamehere1', 'savemovieurl', 'movieurlhere1')")
      conn.commit()
      c.close()
      conn.close()
  
  
  
  def dynamic_data_entry(argument) :
      unix = time.time()
      date = str(datetime.datetime.fromtimestamp(unix).strftime('%Y-%m-%d %H: %M: %S'))
      keyword = 'keyword_string'
      movieurl = 'bing.com'
      value = random.randrange(0,10)
      savemovieurl2 = 'testimageurl.com'
      print argument
      c.execute("INSERT INTO movies (unix, datestamp, keyword, value, moviename, movieimage, movieurl) VALUES (?, ?, ?, ?, ?, ?, ?)", (unix, date, keyword, value, movie, savemovieurl2, movieurl))
      conn.commit()
  
  create_table()
  #data_entry()
  
  for i in range(10) :
      dynamic_data_entry(savemovieurl)
      time.sleep(1)
  c.close()
  conn.close()
  
  
  
  if __name__=="__main__":
      tmdb_posters(imdb_id_input)
  </code></pre>