How does Python print a variable that is out of scope
<p>I have the following function in Pyton that seems to be working:</p>

<pre><code>def test(self):
    x = -1
    # why don't I need to initialize y = 0 here?
    if (x &lt; 0):
        y = 23

    return y
</code></pre>

<p>But for this to work why don't I need to initialize variable y? I thought Python had block scope so how is this possible? </p>

<p>This appears to be a simple misunderstanding about <a href="http://stackoverflow.com/q/291978/674039">scope in Python</a>.  Conditional statements don't create a scope.  The name <code>y</code> is in the local scope inside the function, because of this statement which is present in the syntax tree:</p>

<pre><code>y = 23
</code></pre>

<p>This is determined at function definition time, when the function is parsed.  The fact that the name <code>y</code> might be used whilst unbound at runtime is irrelevant.  </p>

<p>Here's a simpler example highlighting the same issue:</p>

<pre><code>&gt;&gt;&gt; def foo():
...     return y
...     y = 23
... 
&gt;&gt;&gt; def bar():
...     return y
... 
&gt;&gt;&gt; foo.func_code.co_varnames
('y',)
&gt;&gt;&gt; bar.func_code.co_varnames
()
&gt;&gt;&gt; foo()
# UnboundLocalError: local variable 'y' referenced before assignment
&gt;&gt;&gt; bar()
# NameError: global name 'y' is not defined
</code></pre>

python block