Thursday, 19 January 2017

Python Tutorial - 15 (variable scope)



In this video tutorial I have shown how a Variable Scope works in python.
Welcome guys to python tutorial part 15.

So today we will be talking about variable scope.

A variable scope is nothing but understanding where to put your variables inside your code.

Say there is a simple program like we had done in the last few tutorials - 

a = 123

def sai():

    print (a)

def naik():

    print (a)

sai()
naik()

here "a=123" is a variable that we have created

"def sai()" is a simple definition (my name)

"print (a)" we have to print the variable right...

so same for "def naik():"

Now we call out the program by saying "sai()"

OK now the variable is at the top. Say if we put it inside the def.

def sai():

    a = 123

    print (a)

def naik():

    print (a)

sai()
naik()


When we print this out, we will get an error.


The error will be for the second def.

That's because the variable is not read by the second def, while it is inside the first def.

So we should be very careful when putting our variables in programes.

Ok guys thanks for reading. 



You may want to see these - 







      


No comments:

Post a Comment