In [ ]:
%autosave 0

Name space and Scope

Each Function has its own Name Space. Variables in main routine are Global variables and can be referred from Functions, but NOT changeable. Builtin function locals() and globals() can be used to check the variables in each Name space.


In [ ]:
# Function can access(Read) global variable
def f():
    print('x of f() =', x, id(x))
    
x = 100
f()
print('x of main() =', x, id(x))

In [ ]:
# if same variable name is used in Function and value is written before read
# another object is created
def f():
    x = 1
    print('x of f() =', x, id(x))
    
x = 100
f()
print('x of main() =', x, id(x))

In [ ]:
# if function try to update global variable, it's error
def f():
    x += 1
    print('x of f() =', x, id(x))
    
x = 100
f()
print('x of main() =', x, id(x))