abc abc - 10 months ago 42
Python Question

Variable scope in case of an exception in python

while True:
except Exception as e:

print e

Gives: integer division or modulo by zero

I thought scope of
is within the
block and it will not be accessible in the outside
statement. What did I miss ?

Answer Source

Simple: while does not create a scope in Python. Python has only the following scopes:

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

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

tl;dr: Python is not C.