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?
A variable declared at the top of a program or outside of a function is considered a global scope variable. Let's see an example of a global scope variable. In the above program, variable a is declared at the top of a program and is a global variable. It means the variable a can be used anywhere in the program.
The scope of a variable is the region of your program in which it is defined. A global variable has global scope -- it is defined everywhere in your JavaScript code. On the other hand, variables declared within a function are defined only within the body of the function.
Scopes are very important because they determine if a variable/method is visible or not. Also, scopes help create a tidy and clean global namespace, because you can “hide” your variables in a subscope.
Summary. PHP has four types of variable scopes including local, global, static, and function parameters.
Python does not have block scope. Any variables defined in a function are visible from that point only, until the end of the function.
The Devil is in the Details
Naming and binding
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With