


Khusboo Tayal
In Python, scope refers to the region of the code where a variable is recognized. Understanding scope is crucial because it determines the accessibility and lifetime of variables in different parts of your program.
Python has four main types of scopes, collectively known as the LEGB Rule:
| Scope | Description |
|---|---|
| L - Local | Names defined inside a function |
| E - Enclosing | Names in the local scope of enclosing functions |
| G - Global | Names defined at the top level of a module or declared global |
| B - Built-in | Names preassigned in Python (e.g., len, print) |
Variables declared inside a function are local to that function and cannot be accessed from outside.
def my_function():
x = 10
print("Local x:", x)
my_function()
# print(x) # This will raise an error
Variables declared outside of all functions are global and accessible from anywhere in the file.
x = 50
def my_function():
print("Global x inside function:", x)
my_function()
print("Global x outside function:", x)
To modify a global variable inside a function, use the global keyword:
x = 10
def modify():
global x
x = 20
modify()
print("Modified global x:", x)
When a function is nested inside another, the inner function can access variables from the enclosing (outer) function’s scope using nonlocal.
def outer():
x = "outer"
def inner():
nonlocal x
x = "inner"
print("Inner:", x)
inner()
print("Outer:", x)
outer()
Python has some built-in functions and variables available in the global namespace:
print(len("Hello")) # 'len' is a built-in function
You can view all built-in names using:
print(dir(__builtins__))
def outer():
message = "Hello"
def inner():
print(message)
inner()
outer()
In this example, message is not in the local scope of inner(), but it’s available due to the enclosing scope of outer().
Understanding Python scope is essential for writing clean and efficient code. The LEGB rule helps determine where variables can be accessed or modified, which is particularly useful in larger programs or projects involving nested functions and modules.
Q1: What is the LEGB rule in Python?
It stands for Local, Enclosing, Global, and Built-in—describing the order in which Python searches for variable names.
Q2: Can I access a local variable from another function?
No, local variables are limited to the function in which they are defined.
Q3: What happens if a variable is not found in any scope?
Python will raise a NameError.
Subscribe to our newsletter to get the latest Python tutorials, project ideas, and updates right to your inbox.
#python #pythonscope #localscope #globalscope #nonlocal #LEGB #learnpython #pythonbeginners #pythonvariables #pythontutorial