Local Variables
intermediate20 minLearning objectives
- Explain variable scope
- Distinguish between local and global variables
- Describe the lifetime of local variables
- Avoid common scope-related programming errors
Learn
AQA 4.1.1.13 — Local variables, scope and lifetime
Retrieval: the previous lesson's classify function used a variable called classification — this lesson explains exactly where that variable actually "lives", and why it can't be accessed from outside classify.
A local variable is created inside a function and only exists — only has scope — within that function. Its lifetime begins when the function is called and ends the moment the function finishes running; Python then discards it entirely.
def calculate_area(width, height):
area = width * height # area is local to calculate_area
return area
result = calculate_area(4, 5)
print(result) # 20 - fine, this is the returned value
print(area) # NameError! area only exists inside calculate_area
Common mistake
Assuming a variable created inside one function is visible inside another, or outside all functions, simply because it was defined "somewhere earlier" in the file. Python's scope rules don't work by position in the file — they work by which function's body the variable was created in. Two different functions can even each have their own local variable with the exact same name, and they won't interfere with each other at all:
def function_a():
value = "A's value"
print(value)
def function_b():
value = "B's value" # a completely different variable, despite the same name
print(value)
function_a() # A's value
function_b() # B's value
Trace it — when is each variable created and destroyed?
def square(n):
result = n * n
return result
print(square(3))
print(square(5))
| Call | n created | result created | Both destroyed |
|---|---|---|---|
square(3) | when the call starts, n = 3 | after result = n * n runs, result = 9 | when square(3) returns |
square(5) | a fresh n = 5 — nothing left over from the previous call | a fresh result = 25 | when square(5) returns |
Each call gets entirely new local variables — nothing persists between calls unless it's explicitly returned and captured by the caller.
Debug it yourself
def get_username(first, last):
username = (first[0] + last).lower()
return username
print(f"Welcome, {username}!") # this line has a scope bug - find and fix it
Identify why the print line fails, and rewrite the code so it correctly prints the generated username.
Challenge
Produce a short summary (a comment or a small table in your code) explaining, for a function with two parameters and one local variable declared inside it, exactly when each of those three names is created and when each is destroyed across two separate calls to the function.
Looking ahead: the next lesson looks at the opposite case — variables declared outside any function, which behave completely differently.