Scope and Global
Scope determines where a variable can be accessed. Python has four scope levels: local, enclosing, global, and built-in (LEGB rule). Understanding scope helps you avoid unintended variable overwrites.
Local Scope
Variables defined inside a function are local to that function.
def my_func():
x = 10 # local variable
print(x)
my_func()
# print(x) # NameError: x is not defined
Global Scope
Variables defined outside any function are global. Use the `global` keyword to modify a global variable inside a function.
count = 0 # global
def increment():
global count
count += 1
increment()
print(count) # 1
Enclosing (nonlocal) Scope
When you have nested functions, inner functions can use `nonlocal` to modify variables from the outer function.
def outer():
msg = "Hello"
def inner():
nonlocal msg
msg = "Hi"
inner()
print(msg) # Hi
outer()
Built-in Scope
Built-in names like `print`, `len` are always available.
Two Minute Drill
- LEGB rule: Local → Enclosing → Global → Built‑in.
- Use `global` to modify global variables inside functions.
- Use `nonlocal` to modify variables in enclosing (non‑global) scopes.
- Accessing a variable without declaration reads from the nearest scope.
Need more clarification?
Drop us an email at career@quipoinfotech.com
