Understanding scope and lifetime of variables is very important in Python. It helps you control where variables can be accessed and how long they exist in memory.
WHAT IS SCOPE?
Scope refers to the region of a program where a variable is accessible.
There are mainly four types of scope in Python:
• Local Scope
• Enclosing Scope
• Global Scope
• Built-in Scope
This is also known as the LEGB rule.
1. LOCAL SCOPE
A variable defined inside a function has local scope. It can only be accessed inside that function.
def greet():
message = "Hello"
print(message)greet()
If you try to access message outside the function, it will give an error.
2. GLOBAL SCOPE
A variable defined outside all functions has global scope. It can be accessed anywhere in the program.
name = "Hira"def display():
print(name)display()
Global variables exist throughout the program.
MODIFYING GLOBAL VARIABLES
To modify a global variable inside a function, use the global keyword.
count = 0def update():
global count
count += 1update()
print(count)
3. ENCLOSING SCOPE
Enclosing scope appears in nested functions. It refers to variables in the outer function.
def outer():
message = "Hello" def inner():
print(message) inner()outer()
The inner() function can access variables from outer().
4. BUILT-IN SCOPE
Built-in scope includes predefined names in Python like print, len, and type. These are always available.
print(len("Python"))
WHAT IS LIFETIME OF A VARIABLE?
Lifetime refers to how long a variable exists in memory.
• Local variables exist only while the function is running
• Global variables exist until the program ends
• Variables are destroyed when they go out of scope
Example:
def test():
x = 10
print(x)test()
After the function finishes, x no longer exists.
IMPORTANT POINTS
• Python follows the LEGB rule to search for variables
• Avoid using too many global variables
• Local variables are safer and better practice
• Use nonlocal keyword to modify enclosing variables
Example of nonlocal:
def outer():
x = 10 def inner():
nonlocal x
x += 5
print(x) inner()outer()
WHY SCOPE AND LIFETIME ARE IMPORTANT
• Prevent variable conflicts
• Improve code readability
• Help manage memory efficiently
• Make large programs easier to control
Understanding scope and lifetime helps you write structured and professional Python programs.