Variable scope refers to the region of a program where a variable is accessible. It determines the visibility and lifetime of a variable. In Python, there are several types of variable scope:
-
Local Scope:
- Variables defined within a function are local to that function. They cannot be accessed outside of it.
def my_function(): x = 10 # Local variable print(x) my_function() # Outputs: 10 # print(x) # This would raise a NameError -
Global Scope:
- Variables defined outside of any function are global variables. They can be accessed from any function within the same module.
x = 20 # Global variable def my_function(): print(x) # Accessing global variable my_function() # Outputs: 20 -
Enclosing Scope:
- This refers to the scope of enclosing functions. If a function is defined inside another function, the inner function can access variables from the outer function.
def outer_function(): x = 30 # Enclosing variable def inner_function(): print(x) # Accessing enclosing variable inner_function() # Outputs: 30 outer_function() -
Built-in Scope:
- This includes names that are pre-defined in Python, such as built-in functions (e.g.,
print(),len()). These are accessible from anywhere in the code.
- This includes names that are pre-defined in Python, such as built-in functions (e.g.,
Summary
- Local variables are accessible only within their function.
- Global variables are accessible throughout the module.
- Enclosing variables are accessible in nested functions.
- Built-in variables are always accessible.
Understanding variable scope is crucial for managing data and avoiding naming conflicts in your code.
