Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

About variable scope?

Tags:

python

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?

like image 216
spitfiredd Avatar asked Oct 11 '13 11:10

spitfiredd


People also ask

What is scope of variable with example?

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.

What is a variable and variable scope?

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.

Why is variable scope important?

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.

What are the four types of variable scopes?

Summary. PHP has four types of variable scopes including local, global, static, and function parameters.


2 Answers

Python does not have block scope. Any variables defined in a function are visible from that point only, until the end of the function.

like image 42
Daniel Roseman Avatar answered Nov 11 '22 04:11

Daniel Roseman


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.

like image 188
Abhijit Avatar answered Nov 11 '22 02:11

Abhijit