Scopes and Name Resolution
Local scope - inside a function
Enclosing scope - from outer function if nested
Global - Top leve script
def serve_chai():
chai_type = "Masala" # local scope
print(f"Inside function {chai_type}")
chai_type = "Lemon"
serve_chai()
print(f"Outside function: {chai_type}")
def chai_counter():
chai_order = "lemon" # Enclosing scope
def print_order():
chai_order = "Ginger"
print("Inner:", chai_order)
print_order()
print("Outer: ", chai_order)
chai_order = "Tulsi" # Global
chai_counter()
print("Global :", chai_order)
NonLocal - The nonlocal keyword is used to modify a variable in an enclosing but non-global scope, which is specifically relevant for nested functions.