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




CCC Online Test 2021 CCC Practice Test Hindi Python Programming Tutorials Best Computer Training Institute in Prayagraj (Allahabad) Best Java Training Institute in Prayagraj (Allahabad) Best Python Training Institute in Prayagraj (Allahabad) O Level NIELIT Study material and Quiz Bank SSC Railway TET UPTET Question Bank career counselling in allahabad Sarkari Naukari Notification Best Website and Software Company in Allahabad Website development Company in Allahabad