Reputation: 3135
I had a math test today and one of the extra credit questions on the test was
product = 1
for i in range(1,7,2):
print i
product = product * i
print i
print product
We were supposed to list out the steps of the loop which was easy; but it got me thinking, why does this program run? the second print i
seems out of place to me. I would think that the i
only exists for the for loop and then get's destroyed so when you call the second print i
there is no variable i
and you get an error.
Why does i
remain a global variable?
Upvotes: 5
Views: 97
Reputation: 63787
The Devil is in the Details
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.
Or in simple words, a for loop
is not a block
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. If the definition occurs in a function block, the scope extends to any blocks contained within the defining one, unless a contained block introduces a different binding for the name.
So any variable defined is visible from the point of definition to the end of scope of the block, function
, module
or class
definition.
Why does i remain a global variable?
From the nomenclature parlance, I will call i
a global variable, if your highlighted code is part of the module rather than a defined function.
Upvotes: 9
Reputation: 600059
Python does not have block scope. Any variables defined in a function are visible from that point only, until the end of the function.
Upvotes: 0