Variable scope in case of an exception in python
<pre><code>while True:
  try:
    2/0
  except Exception as e:
    break

print e      
</code></pre>

<p>Gives: integer division or modulo by zero</p>

<p>I thought scope of <code>e</code> is within the <code>while</code> block and it will not be accessible in the outside <code>print</code> statement. What did I miss ?</p>

<p>Simple: <code>while</code> does not create a scope in Python. Python has only the following scopes:</p>

<ul>
<li>function scope (may include closure variables)</li>
<li>class scope (only while the class is being defined)</li>
<li>global (module) scope</li>
<li>comprehension/generator expression scope</li>
</ul>

<p>So when you leave the <code>while</code> loop, <code>e</code>, being a local variable (if the loop is in a function) or a global variable (if not), is still available.</p>

<p>tl;dr: Python is not C.</p>

python python-2.7 exception