Jun 24, 2018

Python Variables Scope

#!/usr/local/bin/python2.7

'''
    File name: python_scope.py
    Author: Prabhath Kota
    Date: June 22, 2018
    Python Version: 2.7
'''

'''
The scope of a variable refers to the places that you can see or access a variable.
If you define a variable at the top level of your script or module, this is a global variable
Module/global scope is a read-only shadow within the local function/method scope:
You can access it, providing there's nothing declared with the same name in local scope, but you can't change it.
'''

variable = 100
variable_new = 1111

def func_with_global_access():
    global variable
    print('variable inside function is : ', variable) #100
    variable = 200
    variable_new = 2222 #Local
    print('variable inside function - changed to : ', variable) #200
    print('variable_new inside function - changed to : ', variable_new) #2222

def func_without_global_access():
    try:
        print('variable_new inside fucntion - changed to : ', variable_new) #1111
        variable_new += 100
        """
        #Local variable 'variable_new' referenced before assignment
        #This is because module/global scope is a read-only shadow within the local function/method scope:
        #You can access it, providing there's nothing declared with the same name in local scope,
        #but you can't change it.
        """
        print('variable_new inside fucntion - changed to : ', variable_new) #2222
    except Exception, e:
        print e #local variable 'variable_new' referenced before assignment

print '----------------Global variable----------------------'
print ('variable outside is : ', variable) #100
func_with_global_access()
print ('variable outside is : ', variable) #200
print ('variable_new outside is : : ', variable_new) #1111

print '----------------Local variable----------------------'
print ('variable_new outside is : ', variable_new) #1111
func_without_global_access()
print ('variable_new outside is : ', variable_new) #1111


No comments:

Post a Comment