This logo isn't an ad or affiliate link. It's an organization that shares in our mission, and empowered the authors to share their insights in Byte form.
Rumie vets Bytes for compliance with our
Standards.
The organization is responsible for the completeness and reliability of the content.
Learn more
about how Rumie works with partners.
Ever wonder how video games remember your progress?
How do they remember your character level, items you've collected, or even your high score? It all comes down to variables — bits of information the game stores and uses throughout your playthrough.
But a special kind of variable called a "global variable" acts like a central hub, accessible by any part of the game!
Take a dive into the world of Python global variables and understand when and how to use them effectively.
What are Variables?
A variable is like a hashtag on social media. You can use it to label and categorize information in your code. 🏷️
Just like a hashtag can show up in multiple posts, the information stored in a variable can be used in different parts of your program. 🗃️
Like a hashtag, your variable needs a clear and descriptive name (like "high_score" or "userName"), so it's easy to understand what information it holds. ✍️
And whenever you need to access that information, just use the variable's name — like calling out a specific hashtag to find relevant content. 🔎
Did you know?
The concept of variables in programming dates back to the 1950s with the development of the first high-level programming languages like Fortran. Back then, programmers had to manually manage memory, so variables were a revolutionary idea that simplified coding.
Local vs. Global Variables in Python
Imagine a program you're coding is an office building.
Local Variables = Personal Desk Drawer
Each employee has their own desk drawer. The things in this drawer are only available to the person who sits at that desk. No one else in the building has access to these items unless they are specifically at that desk.
This is like a local variable, which can only be accessed within the function where it's defined.
Global Variables = Office Supplies Room
The office supplies room is accessible to everyone working in the building. Anyone can go in, take what they need, or put something back. These supplies are available to everyone, no matter which room or floor they work on.
This is like a global variable, which can be accessed and modified from anywhere in the program.
Did you know?
Python global variables can be a bit like "celebrity" variables — they're known everywhere in your program, but if you want to change them inside a function, you have to make a special announcement with the 'global' keyword!
Comparing Local & Global Variables
Local Variables
Scope: Local variables are defined within a function and can only be accessed within that function.
Lifetime: Local variables exist only during the execution of the function. Once the function finishes execution, local variables are destroyed.
Declaration: Local variables are typically declared within a function using standard variable assignment.
Accessibility: Local variables are not accessible outside the function where they are defined.
Memory: Local variables are stored in the stack memory — imagine a stack of plates. You can only add or remove from the top of the stack.
Global Variables
Scope: Global variables are defined outside a function and can be accessed from any part of the program.
Lifetime: Global variables exist for the entire duration of the program.
Declaration: Global variables are declared outside of all functions, typically at the beginning of the script.
Accessibility: Global variables are accessible throughout the program, provided the global keyword is used to modify them within a function.
Memory: Global variables are stored in the heap memory — imagine a pile of building blocks. You can take any block you want at any time.
When to Use Python Global Variables
Global variables in Python can be useful in some situations, but they should be used carefully to avoid problems in your code.
Using a global variable might make sense for:
Storing Important Configurations and Settings
If you have a value that many parts of your program need to use, like a website address or a specific number that doesn’t change, you can store it as a global variable.
Sharing Information Between Functions
If you have a piece of information that needs to be shared and updated by different functions in your program, you can use a global variable.
Setting Up Modes or Flags
If your program has different modes (like "debug mode" for testing), you can use a global variable to keep track of the mode and change how the program behaves.
If you want to explore this in more detail, read about deciding when to use Python global variables.
Best Practices for Using Python Global Variables
Use them sparingly: Too many global variables can make your program hard to understand. Only use them when necessary to avoid confusion and potential bugs. 🪳
Prefer constants: Use global variables for values that don’t change (constants) to make your code easier to understand. 💎
Keep them organized: Group related global variables together to keep your code neat. For example, put all settings in one place. 🗃️
Test Your Knowledge
In which of the following situations is it appropriate to use a global variable in Python?
A. To store a constant value like PI = 3.14 that needs to be used in multiple functions.
B. To keep track of the current score in a game that needs to be updated by several functions.
C. To store a temporary result calculated inside a loop, such as the sum of numbers.
D. To set a flag for enabling debug messages, which different parts of your program can check.
Quiz
In which of the above situations is it appropriate to use a global variable in Python? Choose all that apply:
C is incorrect because temporary results should be kept as local variables. A and B are correct because they need to be accessed by multiple parts of the game. D is correct because it influences how different parts of the program behave.
Take Action
To deepen your understanding, explore the following steps:
This Byte has been authored by
Samantha Markham
Instructional Designer/eLearning Developer/Teacher
MA