abc abc - 1 year ago 70
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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download