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>It seems that you misunderstood this part of <a href="https://docs.python.org/3/reference/executionmodel.html" rel="nofollow" title="4. Execution model">Python's documentation</a>:</p>

<blockquote>
  <p>A Python program is constructed from code blocks. A block is a piece of Python program text that is executed as a unit. The following are blocks: a module, a function body, and a class definition.<br>
  ...<br>
  A scope defines the visibility of a name within a block. If a local variable is defined in a block, its scope includes that block.</p>
</blockquote>

<p>So in this case block is <em>something completely different</em> from visual blocks of your code. Thereby <code>if</code>, <code>for</code>, <code>while</code> statements doesn't have their own scopes. But it is worth noting that <strong>comprehensions and generator expressions are implemented using a function scope</strong>, so they have their own scopes.</p>

python block