Monday, 21 October 2013

SCOPE

There are mainly two types of scopes for python variables:

  • Local scope
  • Global scope
Global variables are accessible from all functions whereas local variables are accessible only from the function where it is declared.
Consider the following example.
----------------------------------------------------------------------------------------------------------------------------------
x = 1

def fun():
    x = 2
    print x

fun()
print x

Here the output is
2
1
-----------------------------------------------------------------
First the function fun() is invoked, when the print x statement is encountered, it looks for local variables named x if found it prints the value of local x if not it goes for global x.Since in this problem local x is available the value of global x is overwritten by local x within the function.
-----------------------------------------------------------------

x = 1

def fun():
    p = 2
    print p

fun()
print x
print p #this gives an error

Here the output is
2
1
Traceback (most recent call last):
  File "nested_scope.py", line 7, in 
    print local_var  # this gives an error
NameError: name 'local_var' is not defined
-----------------------------------------------------------------
If at all you invoke global variable within a function, if you declare another variable with the same name, then the global value will be over written(only within the function).
For eg:
-----------------------------------------------------------------
x = 1

def fun():
    global x
    x = 10
    print x

fun()

print x
 
The output will be:
10
10
-----------------------------------------------------------------

0 comments:

Post a Comment