4 5 Scope of Variables Explained
Key Concepts
The scope of variables in Python determines where in the code a variable is accessible. The key concepts include:
- Local Scope
- Global Scope
- Enclosing Scope
- Built-in Scope
1. Local Scope
Variables defined inside a function have local scope and are accessible only within that function. They are created when the function is called and destroyed when the function returns.
Example:
def my_function(): local_var = 10 # Local variable print(local_var) my_function() # Output: 10 # print(local_var) # This will cause an error
2. Global Scope
Variables defined outside of any function or class have global scope and are accessible throughout the entire program. They are created when the program starts and destroyed when it ends.
Example:
global_var = 20 # Global variable def my_function(): print(global_var) my_function() # Output: 20 print(global_var) # Output: 20
3. Enclosing Scope
Enclosing scope refers to variables defined in the outer function of a nested function. These variables are accessible in the inner function but not in the global scope.
Example:
def outer_function(): enclosing_var = 30 # Enclosing variable def inner_function(): print(enclosing_var) inner_function() outer_function() # Output: 30 # print(enclosing_var) # This will cause an error
4. Built-in Scope
Built-in scope includes names that are pre-defined in Python, such as keywords, functions, and exceptions. These names are accessible anywhere in the program without needing to define them.
Example:
print("Hello, World!") # 'print' is a built-in function # No need to define 'print'
Putting It All Together
Understanding the scope of variables is crucial for writing efficient and error-free Python code. By knowing where variables are accessible, you can avoid naming conflicts and ensure that your code behaves as expected.
Example:
global_var = 50 # Global variable def outer_function(): enclosing_var = 60 # Enclosing variable def inner_function(): local_var = 70 # Local variable print(global_var, enclosing_var, local_var) inner_function() outer_function() # Output: 50 60 70