Strange behavior of python's exec function
<p>I think that below code fully describes the problem. Why in the Test2 function x has not been defined? Why the Test3 function does not return an error?</p>

<pre><code>&gt;&gt;&gt; def Test1():
exec('x=2')
print(str(x))


&gt;&gt;&gt; Test1()
2
&gt;&gt;&gt; def Test2():
global x
exec('x=2')
print(str(x))


&gt;&gt;&gt; Test2()

Traceback (most recent call last):
File "&lt;pyshell#39&gt;", line 1, in &lt;module&gt;
Test2()
File "&lt;pyshell#38&gt;", line 4, in Test2
print(str(x))
NameError: global name 'x' is not defined

&gt;&gt;&gt; def Test3():
global x
x=2
print(str(x))

&gt;&gt;&gt; Test3()
2
</code></pre>
