title: Behavior of exec function in Python 2 and Python 3
body: <p>Following code gives different output in <code>Python2</code> and in <code>Python3</code>:</p>
  
  <pre><code>from sys import version
  
  print(version)
  
  def execute(a, st):
      b = 42
      exec("b = {}\nprint('b:', b)".format(st))
      print(b)
  a = 1.
  execute(a, "1.E6*a")
  </code></pre>
  
  <p><code>Python2</code> prints:</p>
  
  <pre><code>2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)]
  ('b:', 1000000.0)
  1000000.0
  </code></pre>
  
  <p><code>Python3</code> prints:</p>
  
  <pre><code>3.2.3 (default, Apr 11 2012, 07:15:24) [MSC v.1500 32 bit (Intel)]
  b: 1000000.0
  42
  </code></pre>
  
  <p>Why does <code>Python2</code> bind the variable <code>b</code> inside the <code>execute</code> function to the values in the string of the <code>exec</code> function, while <code>Python3</code> doesn't do this? How can I achieve the behavior of <code>Python2</code> in <code>Python3</code>? I already tried to pass dictionaries for globals and locals to <code>exec</code> function in <code>Python3</code>, but nothing worked so far.</p>
  
  <p><strong>--- EDIT ---</strong></p>
  
  <p>After reading Martijns answer I further analyzed this with <code>Python3</code>. In following example I give the <code>locals()</code> dictionay as <code>d</code> to <code>exec</code>, but <code>d['b']</code> prints something else than just printing <code>b</code>.</p>
  
  <pre><code>from sys import version
  
  print(version)
  
  def execute(a, st):
      b = 42
      d = locals()
      exec("b = {}\nprint('b:', b)".format(st), globals(), d)
      print(b)                     # This prints 42
      print(d['b'])                # This prints 1000000.0
      print(id(d) == id(locals())) # This prints True
  a = 1.
  execute(a, "1.E6*a")
  
  3.2.3 (default, Apr 11 2012, 07:15:24) [MSC v.1500 32 bit (Intel)]
  b: 1000000.0
  42
  1000000.0
  True
  </code></pre>
  
  <p>The comparison of the ids of <code>d</code> and <code>locals()</code> shows that they are the same object. But under these conditions <code>b</code> should be the same as <code>d['b']</code>. What is wrong in my example?</p>