Understanding variable scope is crucial for avoiding unexpected behavior in your programs. Scope refers to the region of a program where a variable is accessible. In Python, variables typically have either local or global scope.
Local Scope
Variables defined inside a function are said to have local scope. They can only be accessed from within that function. Once the function finishes execution, these local variables cease to exist.
Example:
pythondef my_function(): local_var = 10 # This is a local variable print(f"Inside function: {local_var}") my_function() # print(local_var) # This line would cause a NameError, as local_var is not defined outside the function # Output: # Inside function: 10 # NameError: name 'local_var' is not defined
Each time a function is called, a new local scope is created for that call. This means that variables in one function's local scope don't interfere with variables of the same name in another function's local scope.
Global Scope
Variables defined outside of any function (at the top level of a script) are said to have global scope. They can be accessed from anywhere in the program, both inside and outside functions.
Example:
pythonglobal_var = 20 # This is a global variable def another_function(): print(f"Inside function, accessing global: {global_var}") print(f"Outside function, accessing global: {global_var}") another_function() # Output: # Outside function, accessing global: 20 # Inside function, accessing global: 20
Modifying Global Variables Inside a Function (global keyword)
By default, if you try to assign a new value to a variable inside a function, Python treats it as a new local variable, even if there's a global variable with the same name. To explicitly modify a global variable from within a function, you must use the global keyword.
Example without global (creates a new local variable):
pythonx = 10 # Global variable def func_no_global(): x = 5 # This creates a NEW local variable 'x', it does NOT modify the global 'x' print(f"Inside func_no_global: {x}") func_no_global() print(f"Outside function: {x}") # The global x remains unchanged # Output: # Inside func_no_global: 5 # Outside function: 10
Example with global (modifies the global variable):
pythony = 10 # Global variable def func_with_global(): global y # Declare intent to modify the global variable 'y' y = 5 # This now modifies the GLOBAL 'y' print(f"Inside func_with_global: {y}") func_with_global() print(f"Outside function: {y}") # The global y has been modified # Output: # Inside func_with_global: 5 # Outside function: 5
Best Practice: While the global keyword exists, it's generally good practice to minimize its use. Relying heavily on global variables can make code harder to understand, debug, and maintain, as functions can have 'side effects' that are not obvious from their parameters or return values. It's often better to pass variables into functions as arguments and return modified values if needed.
Enclosing Scope (for nested functions - brief mention)
Python also has an 'enclosing' or 'nonlocal' scope for variables in nested functions. Variables in an enclosing function's scope are accessible to inner functions. The nonlocal keyword is used to modify variables in this enclosing scope. This is a more advanced topic and less common for beginners, but it's good to be aware that it exists beyond local/global.
Understanding scope is fundamental to writing correct and predictable Python code. It helps you manage data flow and avoid unintended interactions between different parts of your program.
Key Takeaways:
- Local scope: Variables defined inside a function, accessible only within that function.
- Global scope: Variables defined outside any function, accessible everywhere.
- Functions can read global variables by default.
- To modify a global variable from inside a function, you must use the
globalkeyword. - Minimize the use of
globalfor cleaner, more predictable code.