Functions, Parameters, and Visibility Rules
What Is Variable Scope?
Scope determines where in your program a variable can be accessed. In Python, scope is governed by the LEGB Rule:
- Local – Inside the current function
- Enclosing – In a nested function’s outer function
- Global – At the top level of the module (outside all functions)
- Built-in – Predefined names like
len,print,range
When Python looks up a variable, it searches in this exact order.
Local vs Global Variables
1. Local Variable (Inside Function)
def my_function():
x = 10 # local variable
print("Inside:", x)
my_function()
# print(x) → ❌ NameError: 'x' is not defined2. Global Variable (Accessible Everywhere)
counter = 0 # global variable
def increment():
print("Before:", counter) # can READ global
increment()
print("After:", counter) # 03. Local Shadows Global (Same Name)
name = "Global Ali"
def greet():
name = "Local Ali" # creates NEW local variable
print("Inside:", name) # Local Ali
greet()
print("Outside:", name) # Global AliModifying Global Variables
By default, you **cannot assign** to a global variable inside a function—Python assumes you want a new local variable. To modify a global, use the global keyword.
4. Modifying Global with
globalscore = 0
def add_points(points):
global score # declare intent to modify global
score += points
add_points(10)
print("Total score:", score) # 105. Without
global – Creates Localtotal = 100
def reset():
total = 0 # creates LOCAL 'total', doesn't change global
reset()
print(total) # Still 100!Function Parameters & Arguments
Parameters are **local variables** initialized when the function is called.
6. Parameters Are Local
def process(value):
value = value * 2 # modifies LOCAL copy
print("Inside:", value)
x = 5
process(x)
print("Outside:", x) # Still 5 (integers are immutable)7. Mutable Arguments (List Example)
def add_item(lst, item):
lst.append(item) # modifies the ORIGINAL list!
my_list = [1, 2]
add_item(my_list, 3)
print(my_list) # [1, 2, 3] — changed!Default Parameter Values
You can specify default values for parameters. If the caller doesn’t provide an argument, the default is used.
8. Basic Default Parameter
def greet(name="Guest"):
print(f"Hello, {name}!")
greet() # Hello, Guest!
greet("Sara") # Hello, Sara!9. Multiple Defaults
def create_profile(name, age=18, city="Unknown"):
return f"{name}, {age} years old, from {city}"
print(create_profile("Ali"))
# Ali, 18 years old, from Unknown
print(create_profile("Omar", 25, "Dubai"))
# Omar, 25 years old, from Dubai10. ⚠️ Dangerous Default: Mutable Objects
# ❌ NEVER do this:
def add_student(name, roster=[]): # mutable default!
roster.append(name)
return roster
# First call
class1 = add_student("Ali")
print(class1) # ['Ali']
# Second call — BUG! Uses same list
class2 = add_student("Sara")
print(class2) # ['Ali', 'Sara'] ← unexpected!11. ✅ Safe Default for Mutable Objects
def add_student(name, roster=None):
if roster is None:
roster = [] # create new list each time
roster.append(name)
return roster
class1 = add_student("Ali")
class2 = add_student("Sara")
print(class1) # ['Ali']
print(class2) # ['Sara'] — correct!Keyword Arguments & Flexibility
12. Calling with Keyword Arguments
def describe_pet(animal, name, age=2):
print(f"{name} is a {age}-year-old {animal}.")
# Order doesn't matter with keywords
describe_pet(name="Whiskers", animal="cat", age=3)
# Whiskers is a 3-year-old cat.13. Mixing Positional and Keyword
def send_email(to, subject, body="", urgent=False):
print(f"To: {to}\nSubject: {subject}\nUrgent: {urgent}")
# Valid
send_email("ali@example.com", "Meeting", urgent=True)
# ❌ Invalid: positional after keyword
# send_email(to="ali@example.com", "Meeting")Enclosing Scope (Nested Functions)
14. Reading Enclosing Variable
def outer():
message = "Hello from outer!"
def inner():
print(message) # can READ from enclosing scope
inner()
outer() # Hello from outer!15. Modifying with
nonlocaldef counter():
count = 0
def increment():
nonlocal count # allows modification
count += 1
return count
return increment
inc = counter()
print(inc()) # 1
print(inc()) # 2Best Practices Summary
- Prefer **local variables**—they make functions predictable and testable.
- Avoid
globalunless absolutely necessary (e.g., configuration flags). - Never use **mutable defaults** like
[]or{}—useNoneinstead. - Use **keyword arguments** for clarity, especially with boolean flags.
- Remember: **parameters are local**, and assignment inside a function creates a local variable unless declared
globalornonlocal.
Key Takeaways
- Scope follows **LEGB**: Local → Enclosing → Global → Built-in.
- Functions can **read** global variables but need
globalto **modify** them. - Default parameters provide flexibility—but be cautious with mutable objects.
- Understanding scope prevents bugs and makes code easier to debug and maintain.