In Python, the scope and lifetime of a variable define where the variable can be accessed and how long it exists during the execution of a program.
Scope refers to the region of the code where a variable is visible and can be accessed.
Global Scope:
global_variable = 10
def my_function():
print(global_variable)
my_function() # Output: 10
Local Scope:
def my_function():
local_variable = 5
print(local_variable)
my_function() # Output: 5
# Attempting to access local_variable outside the function will result in an error
Lifetime refers to the duration for which a variable exists in the memory during program execution.
Global Variable Lifetime:
global_variable = 10
def my_function():
print(global_variable)
my_function() # Output: 10
# The global_variable continues to exist even after the function call
Local Variable Lifetime:
def my_function():
local_variable = 5
print(local_variable)
my_function() # Output: 5
# After the function call, local_variable no longer exists
If a local variable has the same name as a global variable, the local variable takes precedence within its scope.
variable = 100 # Global variable
def my_function():
variable = 50 # Local variable with the same name
print(variable)
my_function() # Output: 50
# Accessing variable outside the function will refer to the global variable
Understanding the scope and lifetime of variables is crucial for writing maintainable and bug-free code. It helps prevent unintended variable name clashes and ensures that variables are used in the appropriate context.