Global and Local Variables (OCR A-Level Computer Science): Revision Notes
📚 Revision Notes
Global and Local Variables
Overview
In programming, variables are used to store data values that can be referenced and manipulated during programme execution. Variables can be classified as global or local based on their scope, or the part of the programme where they can be accessed. Understanding the differences, benefits, and drawbacks of global and local variables is crucial for writing efficient and error-free code.
What are Variables?
- Variables are named storage locations in memory used to hold data.
- Scope: Determines where a variable can be accessed within a programme.
Global Variables
- Definition: Variables declared outside of any function, class, or block.
- Scope: Accessible from any part of the programme, including within functions.
- Lifetime: Exist for the entire duration of the programme.
lightbulbExample
Example:
global_var = 10 # Global variable
def display():
print(global_var) # Accessible inside the function
display()
Local Variables
- Definition: Variables declared within a function, class, or block.
- Scope: Accessible only within the block or function where they are defined.
- Lifetime: Exists only while the function or block is executing.
lightbulbExample
Example:
def calculate():
local_var = 5 # Local variable
print(local_var)
calculate()
# print(local_var) # This will cause an error as local_var is not accessible here
Differences Between Global and Local Variables
| Aspect | Global Variables | Local Variables |
|---|---|---|
| Scope | Entire programme | Limited to the function/block where defined |
| Lifetime | Duration of the programme | Duration of the function/block |
| Memory Usage | Occupy memory throughout programme execution | Memory is freed once the function/block ends |
| Accessibility | Accessible by all functions and blocks | Only accessible within the specific function/block |
| Ease of Debugging | Harder to debug due to wide accessibility | Easier to debug due to limited scope |
Benefits and Drawbacks of Global Variables
Benefits of Global Variables
- Easy Sharing of Data: Useful for data that needs to be accessed and modified by multiple functions.
- Persistent Data: Remain in memory throughout the programme, useful for maintaining state.
Drawbacks of Global Variables
- Increased Risk of Errors: Accidental modification by any function can lead to unintended behaviour.
- Harder to Debug and Maintain: Since they can be modified anywhere, it's harder to track changes and bugs.
- Increased Memory Usage: Occupy memory for the programme's entire duration, even if not always needed.
Benefits and Drawbacks of Local Variables
Benefits of Local Variables
- Reduced Risk of Errors: Changes to local variables are confined to a specific function, minimising unintended interference.
- Efficient Memory Usage: Memory is allocated and freed dynamically, reducing overall memory consumption.
- Easier Debugging and Testing: Since their scope is limited, it's easier to isolate and resolve issues.
Drawbacks of Local Variables
- Limited Access: Cannot be accessed outside their defining function or block, requiring additional mechanisms to share data if needed.
- Reinitialisation Overhead: This must be reinitialised each time the function is called, which could impact performance for frequently called functions.
Recognising and Converting Variables
Recognising Global Variables
- Declared outside any function.
- Used or modified directly in multiple functions.
Recognising Local Variables
- Declared inside a function or block.
- Only accessible within that function or block.
Converting Global to Local Variables
- Identify where the global variable is used.
- Pass it as a parameter to functions that need it.
lightbulbExample
Example:
# Using a global variable
score = 0 # Global variable
def update_score():
global score
score += 10
# Converting to local variable
def update_score(local_score):
local_score += 10
return local_score
score = 0 # Initial value
score = update_score(score)
Converting Local to Global Variables
- Identify the variable's use across multiple functions.
- Declare it outside the functions and use the
globalkeyword to modify it inside the function.
lightbulbExample
Example:
def set_global_var():
global global_var
global_var = 10
Note Summary
infoNote
Common Mistakes
- Unintended Modifications: Accidentally modifying a global variable in one function can lead to unexpected behaviour in another.
- Overusing Global Variables: Relying too heavily on global variables can lead to spaghetti code, where the programme's logic is hard to follow.
- Shadowing: Declaring a local variable with the same name as a global variable can cause confusion and bugs.
Example:
x = 10 # Global
def func():
x = 5 # Local variable shadows the global x
print(x) # Prints 5
func()
print(x) # Prints 10
:::
infoNote
Key Takeaways
- Global variables are accessible throughout the programme, providing persistent data storage but increasing the risk of errors and memory usage.
- Local variables are limited to specific functions or blocks, offering better memory efficiency and reducing error risks.
- Understanding when to use global or local variables is essential for writing efficient and maintainable code.
- Programmes can be refactored to switch between global and local variables by using parameters and the
globalkeyword appropriately.