6.6.3 Global and local variables
Scope: Where Variables Exist
A variable's scope is the region of a program where it is accessible. Understanding scope is essential for writing correct programs with subprograms — it determines which variables a function can read and modify.
| Local variable | Global variable | |
|---|---|---|
| Defined | Inside a function | Outside all functions (top level) |
| Accessible | Only within that function | Throughout the program |
| Lifetime | Created when function is called; destroyed when it returns | Exists for the entire program run |
| Best use | Temporary values, intermediate calculations | Constants and shared state needed everywhere |
Scope in Code
HIGH_SCORE = 0 # global variable (mutable state — avoid if possible)
PASS_MARK = 60 # global constant (appropriate use)
def check_score(score):
"""Local variable: result is only needed inside this function."""
result = "Pass" if score >= PASS_MARK else "Fail" # local
return result
def update_high_score(score):
"""Modifies a global variable — requires the global keyword."""
global HIGH_SCORE
if score > HIGH_SCORE:
HIGH_SCORE = score
# Local variables cannot be accessed outside their function
check_score(75)
# print(result) # NameError — result is local to check_score
update_high_score(85)
update_high_score(72)
print("High score:", HIGH_SCORE) # 85 — accessible because it is global
Python scope rules
- Reading a global variable inside a function: allowed without any keyword
- Assigning to a global variable inside a function: requires
global variable_namedeclaration first - Without
global, assignment creates a new local variable that shadows the global
// In C#, variables are scoped to their enclosing block {}
// Class-level fields act as globals within the class
static int highScore = 0; // class-level (global within class)
const int PASS_MARK = 60;
static string CheckScore(int score) {
string result = score >= PASS_MARK ? "Pass" : "Fail"; // local to method
return result;
}
static void UpdateHighScore(int score) {
if (score > highScore) highScore = score; // accesses class-level field
}
// Main
Console.WriteLine(CheckScore(75));
UpdateHighScore(85);
UpdateHighScore(72);
Console.WriteLine("High score: " + highScore);
' Module-level variables act as globals within the module
Dim highScore As Integer = 0
Const PASS_MARK As Integer = 60
Function CheckScore(score As Integer) As String
Dim result As String = If(score >= PASS_MARK, "Pass", "Fail") ' local
Return result
End Function
Sub UpdateHighScore(score As Integer)
If score > highScore Then highScore = score ' accesses module variable
End Sub
' Main
Console.WriteLine(CheckScore(75))
UpdateHighScore(85)
UpdateHighScore(72)
Console.WriteLine("High score: " & highScore)
Why Prefer Local Variables
# Better: pass values through parameters — no global needed
def calculate_discount(price, rate):
"""Local: discounted_price only exists here."""
discounted_price = price * (1 - rate)
return discounted_price
# Worse: using a global variable that any function can accidentally modify
discount_result = 0 # global — any function can corrupt this
def bad_discount(price, rate):
global discount_result
discount_result = price * (1 - rate) # modifies shared global state
The first version is self-contained and safe to call from anywhere. The second version requires callers to know about and manage discount_result, and two simultaneous calls would corrupt each other's results.
Key Takeaways
- Local: defined inside a function; exists only during that call; cannot be accessed outside.
- Global: defined at the top level; accessible throughout; persists for the program's lifetime.
- Python requires
global varnameto assign to a global inside a function; reading is allowed freely. - Prefer passing values as parameters over using global mutable variables — cleaner, safer, more testable.
- Global constants are fine; global mutable variables should be avoided where possible.