#----------- LOCAL / Global variable Scope --------------
globalvar = "Python" # declared as simple variable---> will be consider as global declaration
def someFunction(): #created a function
globalvar = "version 3.6" #value of variable changed locally
print globalvar # will print version 3.6
someFunction() # call to the function
print globalvar # will print Python
def changeGlobalVar():
global globalvar # make variable global
print globalvar #will print Python
globalvar = "--->Change Value" #changed value of variable globally as we declared it global
changeGlobalVar()
print globalvar #will print --->Change Value
#deleting global variable
del globalvar #delete the object
print globalvar # will give an error 'NameError: global name 'globalvar' is not defined'
OUTPUT
root@Avinash:~/python_codes# python variables.py
version 3.6
Python
Python
--->Change Value
Traceback (most recent call last):
File "variables.py", line 26, in <module>
print globalvar
NameError: global name 'globalvar' is not defined
root@Avinash:~/python_codes#
globalvar = "Python" # declared as simple variable---> will be consider as global declaration
def someFunction(): #created a function
globalvar = "version 3.6" #value of variable changed locally
print globalvar # will print version 3.6
someFunction() # call to the function
print globalvar # will print Python
def changeGlobalVar():
global globalvar # make variable global
print globalvar #will print Python
globalvar = "--->Change Value" #changed value of variable globally as we declared it global
changeGlobalVar()
print globalvar #will print --->Change Value
#deleting global variable
del globalvar #delete the object
print globalvar # will give an error 'NameError: global name 'globalvar' is not defined'
OUTPUT
root@Avinash:~/python_codes# python variables.py
version 3.6
Python
Python
--->Change Value
Traceback (most recent call last):
File "variables.py", line 26, in <module>
print globalvar
NameError: global name 'globalvar' is not defined
root@Avinash:~/python_codes#
No comments:
Post a Comment