
PYTHON — Local Enclosing Global Scope in Python
Technology should improve your life… not become your life. — Anonymous

PYTHON — Using Terminal Windows Overview in Python
When working with Python, understanding scope is essential for writing effective and maintainable code. Python utilizes the LEGB rule, which stands for Local, Enclosing, Global, and Built-in scopes. In this tutorial, we’ll focus on exploring the first three scopes: local, enclosing, and global.
Local Scope
The local scope contains names defined inside a function. Each time a function is called, a new local scope is created. Let’s take a look at an example:
def print_total():
total = 0
print(f"From function: total={total}")
print_total() # Output: From function: total=0
print(total) # Throws an error as total is not defined outside the functionIn this example, the variable total is defined within the print_total() function and is accessible only within that function.
Enclosing Scope
The enclosing scope exists for nested functions and is also known as nonlocal scope. Names defined in the enclosing scope are accessible to inner functions. Here’s an example:
def print_total():
total = 5 # Global scope
def inner_print_total():
total = 7 # Enclosing scope
print(f"From inner function: total={total}")
inner_print_total()
print(f"From outer function: total={total}")
print_total() # Output: From inner function: total=7, From outer function: total=5In this example, the variable total is defined in both the enclosing and global scopes, and Python distinguishes between them.
Global Scope
The global scope is the top-level scope in a Python program, and names defined in this scope are visible from anywhere in the code. Here’s how the global scope works:
total = 5 # Global scope
def print_total():
total = 12 # Enclosing scope
def inner_print_total():
total = 7 # Local scope
print(f"From inner function: total={total}")
inner_print_total()
print(f"From outer function: total={total}")
print_total() # Output: From inner function: total=7, From outer function: total=12
print(total) # Output: 5In this example, the variable total is defined in the global, enclosing, and local scopes, and each one maintains its own separate value.
By understanding these three scopes, you can effectively organize and manage variable names in your Python code. In the next lesson, we’ll explore the built-in scope and complete our understanding of the LEGB rule.
In conclusion, understanding the local, enclosing, and global scopes in Python is crucial for writing efficient and well-structured code. By grasping the concept of scope, you can effectively manage variable names in your Python programs. Understanding these scopes is fundamental to writing code that is both clear and maintainable.

