python


Variable Scopes

The scope of a variable refers to the places from where we can see or access a variable.
In Python , there are 4 types of scopes:
1. Local : Inside a function body
2. Enclosing: Inside an outer function’s body . We will discuss it later
3. Global: At the module level
4. Built In: At the interpreter level
In short we pronounce it as LEGB


Global Variable

A variable which is defined in the main body of a file is called a global variable.
It will be visible throughout the file

Local Variable

A variable which is defined inside a function is local to that function.
It is accessible from the point at which it is defined until the end of the function.
It exists for as long as the function is executing.
Even the parameter in the function definition behave like local variables
When we use the assignment operator (=) inside a function, it’s default behaviour is to create a new local variable – unless a variable with the same name is already defined in the local scope.
Example:


s="I love Python"
def f():
    global s
    s="I love C"
    print(s)
f()
print(s)

Output:

    I love C
    I love C

Example:

s="I love Python"
def f():
    print(s)
    s="I love C"
    print(s)
f()
print(s)

Output:

UnboundLocalError!: 
Local variable s referenced before assignment

Now , this is a special case! . In Python any variable which is changed or created inside of a function is local, if it hasn't been declared as a global variable. To tell Python, that we want to use the global variable, we have to explicitly state this by using the keyword "global"
Example:

a=1
def f():
    print ('Inside f() : ', a)
def g():    
    a = 2
    print ('Inside g() : ',a)
def h():    
    global a
    a = 3
    print ('Inside h() : ',a)
 
print ('global : ',a)
f()
print ('global : ',a)
g()
print ('global : ',a)
h()
print ('global : ',a)

Output:

global : 1
inside f( ):1
global: 1
inside g( ): 2
global : 1
inside h( ): 3
global : 3