All technological notes.
scope:
A variable created inside a function belongs to the local scope of that function, and can only be used inside that function.
print("\n--------Scope--------\n")
def xfunc():
x = 300 # x available only inside the function
print(x)
xfunc()
# print(x) # NameError: name 'x' is not defined
Rule: LEGB
Local: Names assigned in any way within a function (def or lambda), and not declared global in that function.
When a variable is called whithin a function, Python will look for it inside the function first.
print("\n--------Scope: Local Scope--------\n")
# global variable
x = 200
def xfunc(x):
# argument creates a local variable.
# argument copies the value of referenced object.
x = 300 # assign new value to local variable
print(x) # 300, call the local variable
xfunc(x) # call function and pass an argument.
print(x) # 200, here x is a global variable.
When the function has any argument, the argument will create a local variable and copy the value of the referenced object.
print("\n--------Scope: Literal Value--------\n")
x = 200
def xFunc(x):
x = 300
print(x) # 300
xFunc(x)
print(x) # 200, the global value will be the same.
print("\n--------Scope: Reference Type--------\n")
x = [1, 2]
def xFunc(x):
x[0] = 0
print(x) # [0, 2]
xFunc(x)
print(x) # [0, 2], the object outside the function will be affected.
Enclosing Function local:
Variable in the outside function can be access within the inside function.
When a variable is called whithin a function, Python will look for it inside the function first.
print("\n--------Scope: function inside function--------\n")
def xfunc():
x = 300 # local variable
print(x)
def yfunc():
print(x) # call variable outside of yfunc()
yfunc() # call the function inside function
xfunc()
Global(module):
global variable
global scope.When a variable is called whithin a function, Python will look for it inside the function first.
print("\n--------Scope: Global--------\n")
x = 200
def xfunc():
# no x inside the function, Python will call the global variable
print(x) # 200
xfunc()
global Keywordglobal:
print("\n--------'global' Keyword--------\n")
x = 300
def xfunc():
x = 200
def yfunc():
global x # declare that x in local scope is a global variable
x = 200
xfunc()
print(x) # 300 global variable does not change
yfunc()
print(x) # 200 global variable does not change
Built-in(Python):