title: Why doesn't an import in an exec in a function work?
body: <p>I can put an import statement in a string, exec it, and it works (prints a random digit):</p>
  
  <pre><code>code = """
  import random
  def f():
      print random.randint(0,9)
  """
  
  def f():
      pass
  
  exec code
  f()
  </code></pre>
  
  <p>Now, if I put <code>exec code</code> and <code>f()</code> in their own function and call it, it doesn't work.</p>
  
  <pre><code>def test():
      exec code
      f()
  
  test()
  </code></pre>
  
  <p>It says <code>NameError: global name 'random' is not defined</code>.</p>