Core Python · #4 of 11
Functions + Scope
Reusable logic and clean code
Why it matters
Functions keep your logic reusable, testable, and readable.
The idea
A function is a mini-program: input → processing → output. Default arguments turn one function into many; *args / **kwargs make it variadic. Scope follows LEGB: Local → Enclosing → Global → Built-in.
Try it
Default args + keyword args:
def greet(name, greeting="Hello"):
return f"{greeting}, {name}!"
print(greet("Ada"))
print(greet("Linus", greeting="Hi"))
print(greet(greeting="Howdy", name="Margaret"))
*args / **kwargs capture overflow positional and keyword arguments:
def describe(*things, **labels):
for t in things:
print("-", t)
for k, v in labels.items():
print(k, "=", v)
describe("apple", "banana", "cherry", colour="red", taste="sweet")
Scope: a function sees outer names but cannot rebind them without nonlocal / global:
counter = 0
def inc():
global counter
counter += 1
inc(); inc(); inc()
print("counter:", counter)
def outer():
x = 1
def inner():
nonlocal x
x += 10
inner()
print("outer.x:", x)
outer()
Function patterns by data type
A function's shape often follows the type it works on. These three patterns bridge straight into the data-structure lessons:
- list → return a new list:
[x*2 for x in nums] - dict → build with
.get():counts[x] = counts.get(x, 0) + 1 - str → normalize, then compare:
s.lower()
Quick check
- Q: What's the difference between
printandreturn? A:returngives a value back;printjust displays.
Mini drills
- Write
is_even(n). - Write
square_all(nums)using a loop.
Do's and don'ts
- Do keep functions small and focused.
- Don't use mutable default args like
def f(x=[]).
Common mistakes
- Mistake: Forgetting to return a value. Fix: Add
return. - Mistake: Mutating a default list argument. Fix: Use
Noneand create the list inside.
Key takeaways
- Default arguments evaluate ONCE at definition — don't use mutables as defaults.
*args/**kwargsenable forwarding (f(*args, **kwargs)).- LEGB scope: Local → Enclosing → Global → Built-in.
- Pure functions (no side effects) are easier to test and reason about.