Python Global Variables
3 min read ·
In Python, a global variable is a variable that is declared outside a function and can be accessed from anywhere in the program.
Global variables are useful when you want to share data across multiple functions.
What Is a Global Variable?
A variable created outside of all functions is called a global variable.
- It belongs to the global scope
- It can be accessed anywhere in the file
- It exists for the entire lifetime of the program
Accessing Global Variables Inside a Function
You can read a global variable inside a function without any special keyword.
Local vs Global Variable
If a variable is created inside a function, it is a local variable and cannot be accessed outside.
Using the global Keyword
To modify a global variable inside a function, you must use the
global keyword.Global Variables with Same Name as Local
If a variable with the same name exists inside a function, Python treats it as local by default.
When to Use Global Variables
Global variables are useful when:
- Multiple functions need shared data
- Configuration values are required globally
- Constants are defined once and reused
Best Practices for Global Variables
- Use global variables sparingly
- Prefer constants (uppercase names)
- Avoid modifying globals frequently
- Use function parameters when possible
Common Mistake
Trying to modify a global variable without
global keyword.Exercise
- Create a global variable and access it inside a function
- Modify a global variable using
globalkeyword - Try creating a local variable with the same name