Global vs Local Variable in Python: Key Differences and Usage
global variable is defined outside functions and accessible throughout the program, while a local variable is defined inside a function and only accessible within that function. Local variables exist temporarily during function execution, whereas global variables persist for the program's lifetime.Quick Comparison
Here is a quick side-by-side comparison of global and local variables in Python.
| Aspect | Global Variable | Local Variable |
|---|---|---|
| Definition | Declared outside any function | Declared inside a function |
| Scope | Accessible anywhere in the program | Accessible only within the function |
| Lifetime | Exists as long as the program runs | Exists only during function execution |
| Modification | Can be modified inside functions using global keyword | Modified freely inside its function |
| Use case | Store data shared across functions | Store temporary data for function tasks |
Key Differences
A global variable is created outside of all functions and can be accessed by any part of the program. This means if you declare a variable at the top level of your script, it is global. To modify a global variable inside a function, you must use the global keyword; otherwise, Python treats it as a new local variable.
On the other hand, a local variable is created inside a function and only exists while that function runs. It cannot be accessed outside the function, which helps keep data isolated and prevents accidental changes from other parts of the program.
Understanding these differences is important because using global variables carelessly can lead to bugs and harder-to-maintain code, while local variables promote safer, modular programming.
Code Comparison
This example shows how a local variable works inside a function:
def greet(): message = "Hello from local variable!" print(message) greet() # print(message) # This would cause an error because 'message' is local
Global Variable Equivalent
This example shows how a global variable is accessed and modified inside a function:
message = "Hello from global variable!" def greet(): global message message = "Changed inside function" print(message) greet() print(message)
When to Use Which
Choose local variables when you want to keep data limited to a function to avoid side effects and make your code easier to understand and debug. Use global variables when you need to share data or state across multiple functions or parts of your program, but do so sparingly and clearly to prevent confusion and bugs.
Key Takeaways
global keyword to modify global variables inside functions.