Understanding the scope and lifetime of variables is crucial for effective programming in Python. In Python, the lifetime of a variable is determined by its scope, which can be global, local, or nonlocal.
Example:
global_var = "I am a global variable"
def my_function():
print(global_var)
my_function() # Output: I am a global variable
Example:
def my_function():
local_var = "I am a local variable"
print(local_var)
my_function() # Output: I am a local variable
# print(local_var) # This would raise an error as local_var is not defined outside the function
Enclosing scope refers to the scope of variables in enclosing functions, applicable in nested functions. These variables can be accessed but not modified in the inner functions unless declared with the nonlocal keyword.
Example:
def outer_function():
enclosing_var = "I am an enclosing variable"
def inner_function():
nonlocal enclosing_var
enclosing_var = "I have been modified"
print(enclosing_var)
inner_function()
print(enclosing_var)
outer_function()
# Output:
# I have been modified
# I have been modified
The built-in scope is a special scope that contains Python's built-in functions and exceptions. These are always available and can be accessed from any part of the code.
Example:
print(len("Hello")) # Output: 5