Lesson 5: Variable Scope, Parameters & Docstrings
Where a name lives, and how values get into a function • Sections 6.3 (Variable Scope), 6.4 (Parameters), 6.6 (Keyword Args, pass, Docstrings)
Save or Print Notes
Export this study guide as a clean PDF for exam preparation and quick revision.
1. What Is Variable Scope?
Scope is the region of a program where a variable name can be accessed. Every call to a function gets its own private workspace (frame), and names created in that frame are invisible from outside.
| Feature | Local Variable | Global Variable |
|---|---|---|
| Created by | An assignment inside a def function |
An assignment outside all defs |
| Visible to | That one specific function call only | Every function across the entire file |
| Lifetime | Until the function returns (destroyed on exit) | The whole run of the program |
| To change it | Just assign to it directly | Requires the global keyword inside a function |
2. Two Memory Regions: Reading vs Shadowing
Reading a Global is Free
Python checks the local frame first. If the variable is not found locally, it automatically checks the global module frame. No special keyword is needed to read a global!
tax = 5 # Global variable
def bill_total(price):
fee = price // 10
# Reads 'tax' from GLOBAL frame:
return price + fee + tax
print(bill_total(200)) # Output: 225
Trying to access
print(fee) outside bill_total raises NameError: name 'fee' is not defined. Use return to send data out!
Shadowing: One Name, Two Boxes
Assigning to a variable inside a function creates a NEW local variable with that name, leaving the global variable completely untouched!
name = "Maryam" # Global box
def show_name():
name = "Khalid" # LOCAL box (shadows global)
print("inside:", name)
show_name()
print("outside:", name)
# Output:
# inside: Khalid
# outside: Maryam
3. The Broken Counter & The global Keyword
Why It Breaks: UnboundLocalError
If Python sees an assignment (e.g. visits = ...) anywhere inside a function, it classifies that variable as local for the entire function body!
visits = 0
def record_visit(page):
visits = visits + 1 # ❌ UnboundLocalError!
print(page, "->", visits)
visits = assigns to visits, Python treats it as a local variable. On the right-hand side, reading visits + 1 attempts to read an uninitialized local variable!
The Fix: The global Keyword
Use global variable_name to tell Python: "Do not create a local variable; write to the module-level global box."
visits = 0
def record_visit(page):
global visits # Modifies global box
visits = visits + 1
print(page, "->", visits)
record_visit("home") # home -> 1
record_visit("menu") # menu -> 2
4. Parameters, Defaults & Keyword Arguments
Parameters vs Arguments
- Parameter: The local variable defined in the function signature (e.g.
def show_grade(course, mark):). - Argument: The actual value handed over at the call site (e.g.
show_grade("infs1201", 88)).
Default Parameters (Optional Arguments)
A default value allows the caller to omit that argument.
def room_cost(hours, rate=25, currency="QR"):
return f"{hours * rate} {currency}"
print(room_cost(2)) # "50 QR"
print(room_cost(2, 40)) # "80 QR"
print(room_cost(2, 40, "USD")) # "80 USD"
def bad(a=1, b): raises SyntaxError: non-default parameter follows default parameter.
Keyword Arguments
You can name the parameter at the call site to skip defaults or reorder arguments.
def mystery(x, y=10, z=20):
return x + y + z
print(mystery(5)) # 35 (x=5, y=10, z=20)
print(mystery(5, z=1)) # 16 (skips y, sets z=1)
mystery(z=1, 5) raises SyntaxError.
5. The pass Keyword & Docstrings
The pass Keyword
pass is a placeholder do-nothing statement. Use it where Python requires an indented block of code syntactically, but you have nothing to execute yet.
def compute_backlog(data):
pass # To be implemented later
result = compute_backlog(120)
print(result) # Output: None
Docstrings: A Living Contract
A string literal written as the FIRST statement inside a function body. Stored in __doc__ and shown by help() and IDE tooltips.
def gpa_points(mark, bonus=0):
"""Convert a mark to GPA points.
Args:
mark (int): Mark out of 100.
bonus (int): Extra points.
Returns:
float: GPA on a 4.0 scale.
"""
total = mark + bonus
return round(total / 25, 1)
help(gpa_points) # Prints formatted docstring!