In computer programming, the scope of a name binding—an association of a value to a variable—is the part of a program where the name binding is valid; that is, the variable can be referred to the specific value.
In short, the scope is the area within which the variable is active.
How does python determine the scope of variables? It uses LEGB rules.
找scope 順序的方法 (LEGB)
LEGB分別為Local、Enclosing、Global、Built-in,python會遵循此規則進行變數搜尋,
只要變數被找到搜尋行動就會停止,如果沒有找到就會出現Error
# scope variable / function block of code 影響範圍
def greet():
name = "Albert"
def hello():
print("Hello, my name is" + name)
def hello2():
print("greeting from hello2.")
hello()
hello2() # hello/hello2 function 只能在greet function 中執行
greet()
hello() # hello function 在外層是無法執行會show NameError: name 'hello' is not defined
-------------------------------------------------------
Hello, my name is Albert
greeting from hello2.
NameError: name 'hello' is not defined # hello function 在外層是無法執行會show NameError: name 'hello' is not defined