There are mainly two types of scopes for python variables:
Consider the following example.
----------------------------------------------------------------------------------------------------------------------------------
The output will be:
10
10
-----------------------------------------------------------------
- Local scope
- Global scope
Consider the following example.
----------------------------------------------------------------------------------------------------------------------------------
x = 1
def fun():
x = 2
print x
fun()
print x
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
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, inprint 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
def fun():
global x
x = 10
print x
fun()
print x






0 comments:
Post a Comment