To modify a global variable from within a function in Python, use the global
keyword before the variable name inside the function. This explicitly tells Python that you are referring to the global variable, not creating a new local variable with the same name.
Here's a breakdown:
Why use the global
keyword?
Without the global
keyword, Python assumes that any variable assigned a value inside a function is a local variable. If you try to modify a global variable without using global
, you'll end up creating a local variable instead, leaving the global variable unchanged.
How to use the global
keyword
- Declare the global variable: Define the variable outside any function.
- Use the
global
keyword inside the function: Inside the function where you want to modify the global variable, use theglobal
keyword followed by the variable name. - Modify the variable: After declaring it as global within the function, you can modify the variable's value.
Example:
# Global variable
global_variable = 10
def modify_global():
global global_variable # Access the global variable
global_variable = 20 # Modify the global variable
print(f"Inside function: global_variable = {global_variable}")
print(f"Before function call: global_variable = {global_variable}")
modify_global()
print(f"After function call: global_variable = {global_variable}")
Output:
Before function call: global_variable = 10
Inside function: global_variable = 20
After function call: global_variable = 20
In this example, the global
keyword ensures that the modify_global
function modifies the global_variable
defined outside the function.
Important Considerations
- Readability: Overuse of global variables can make code harder to understand and maintain. Consider using other techniques like passing variables as arguments or using object-oriented programming principles for better code organization.
- Scope: Understanding variable scope (local vs. global) is crucial for writing correct Python code.
- Alternatives: While
global
works, consider using classes and object attributes as a way to manage state, which often leads to cleaner and more maintainable code, especially in larger projects.