Index
Scope
Scope refers to the region or area in your code where a variable is recognized and can be accessed or used.
π― 4 Types of Variable Scope:
Type | Description |
---|---|
Local | Inside a function |
Enclosing | Inside nested functions |
Global | Outside all functions (entire file) |
Built-in | Pythonβs reserved words/functions |
β 1. Local Scope
A variable declared inside a function.
def greet():
name = "Alice" # Local variable
print("Hello", name)
greet()
# print(name) # β Error: name is not accessible here
π name
is only accessible inside the greet()
function.
β 2. Global Scope
A variable declared outside all functions.
x = 10 # Global variable
def show():
print("x =", x)
show()
print("x outside function =", x)
x = 10 # Global variable
def show():
print("x =", x)
show()
print("x outside function =", x)
π x
can be used everywhere in the program.
β 3. Enclosing Scope (for nested functions)
def outer():
msg = "Hi" # Enclosing variable
def inner():
print(msg) # Accesses enclosing scope
inner()
outer()
π The inner()
function can access msg
from the outer (enclosing) function.
β 4. Built-in Scope
Python has its own built-in functions and keywords like print()
, len()
, etc.
print(len("Hello")) # Built-in functions
These are available everywhere in your code.
π§ Remember: LEGB Rule
Python looks for a variable in the following order:
L β Local
E β Enclosing
G β Global
B β Built-in
β Summary
Scope Type | Where it’s accessible |
---|---|
Local | Only inside a function |
Global | Entire program |
Enclosing | Inside nested functions |
Built-in | Always available |