Junior — Middle
What is the role of scope in the Python language and how does it affect access to variables?
sobes.tech AI
Answer from AI
Scope in Python defines where a variable is accessible for reading and writing. It affects how the interpreter searches for a variable when it is referenced.
The main types of scope are:
- Local — variables declared inside a function, accessible only within it.
- Enclosing — the scope of an outer function, if the function is nested inside another.
- Global — variables declared at the module level.
- Built-in — names defined in Python's standard library.
When referencing a variable, Python searches in the order LEGB (Local, Enclosing, Global, Built-in).
Example:
a = 10 # global variable
def outer():
b = 20 # outer variable
def inner():
c = 30 # local variable
print(a, b, c)
inner()
outer()
To modify a global variable inside a function, use the global keyword:
count = 0
def increment():
global count
count += 1
Scope helps avoid name conflicts and manage variable lifetimes.