Local variables

Local variables


A variable with local scope can be accessed only within the function/block that it is created in. When a variable is created inside the function/block, the variable becomes local to it. A local variable only exists while the function is executing.

Example

X=50

def test ( ):

y = 20

print "Value of x is ‟, X, „; y is ‟ , y

print "Value of x is ‟, X, „ y is „ , y

On executing the code we will get

Value of x is 50; y is 20

The next print statement will produce an error, because the variable y is not accessible outside the function body.

A global variable remains global, till it is not recreated inside the function/block.

Example

x=50

def test ( ):

x=5

y=2

print "Value of x & y inside the function are " , x , y

print "Value of x outside the function is " , x

This code will produce following output:

Value of x & y inside the function are 5 2

Value of x outside the function is 50

If we want to refer to global variable inside the function then keyword global will be prefixed with it.

Example

x=50

def test ( ):

global x

x =2

y = 2

print „Value of x & y inside the function are „ , x , y

print „Value of x outside function is „ , x

This code will produce following output:

Value of x & y inside the function are 2 2

Value of x outside the function is 2

Python : Local variables Program List