0

In this code, why do a and b not get destroyed at the ends of their respective blocks?

flag = True
if flag:
    a = 1

for i in range(2):
    b = 2

print(a, b)

Instead, this code prints 1 2. Why does Python allow this? When can I rely on this behavior?

Prune
  • 76,765
  • 14
  • 60
  • 81
shane
  • 1,742
  • 2
  • 19
  • 36

1 Answers1

5

Read up on the scoping rules for Python. In short, a scope is started with a new module: function, method, class, etc. Mere control flow statements (e.g. if and for) do not start a new scope. The scope of a variable is from its firs definition to the end of that scope.

Since this example has only one scope, each variable is good from its first assignment to the end of the file.

Is that enough to clear up the problem?

Prune
  • 76,765
  • 14
  • 60
  • 81
  • 1
    Note that a variable can be in scope even *before* its definition; that's why the `global` statement is required in something like `def foo(): print x; x=3` if your intention is to output the old value before assigning a new one. (That is, if you don't consider `global x` to be a definition.) – chepner Apr 26 '17 at 21:54
  • Quite correct; I restricted my response to the specific problem, giving a reference to the documentation. – Prune Apr 26 '17 at 22:52