In Python, variables that are declared outside of a function or in the global scope are known as global variables. They can be accessed and modified by any function within the program.
Declaring Global Variables
x = 10 # Global variable
def func():
print(x)
func() # Output: 10
Modifying Global Variables
To modify a global variable inside a function, use the global
keyword:
def func():
global x
x = 20
func()
print(x) # Output: 20
Global Variables vs. Local Variables
Variables declared inside a function are local and cannot affect global variables unless specified:
x = 10
def func():
x = 5 # Local variable
print(x)
func() # Output: 5
print(x) # Output: 10
Best Practices
- Minimize Use: Overuse of global variables can lead to code that is hard to debug.
- Encapsulation: Prefer passing variables as parameters.
- Naming Conventions: Use clear and distinct names for global variables.
Conclusion
Global variables can be useful but should be used judiciously. Understanding how they work helps you write cleaner and more maintainable Python code.