More Functions: Scope, Lambdas & Recursion
Where variables live (local and global scope), functions as values, lambda and sorting with a key, *args and **kwargs, the mutable default trap, and recursion: functions that call themselves.
Scope: where a variable lives
Variables created inside a function are local: they exist only while that call runs, and the rest of the program cannot see them. Variables created outside any function are global: functions can read them. This keeps functions independent: two functions can both use a variable called total without interfering.
rate = 0.1 # global
def with_tax(amount):
total = amount * (1 + rate) # total is local; rate is read from outside
return total
print(with_tax(50))
# print(total) would be a NameError: total only existed inside the call
def change_rate():
rate = 0.5 # this creates a NEW local rate; the global is untouched
return rate
change_rate()
print(rate) # still 0.1Pass values in, return values out
A function can change a global with the global keyword, but avoid it: code where any function might change any variable is very hard to follow and test. The professional habit is simple: everything a function needs comes in as parameters, and everything it produces goes out with return.
Functions are values
A function is an object like any other: you can store it in a variable, put it in a list, or pass it to another function. Many built-ins take a function as a key to decide how to compare items: sorted, min, max.
For a tiny one-line function, lambda writes it without a name: lambda x: x * 2 means "take x, give back x * 2". Use lambdas for short keys; use def for anything longer.
def shout(text):
return text.upper() + "!"
say = shout # no brackets: the function itself
print(say("hello"))
people = [("Sita", 27), ("Leo", 31), ("Mia", 24)]
print(sorted(people, key=lambda p: p[1])) # sort by age
print(max(people, key=lambda p: p[1])[0]) # the oldest person's name
words = ["Banana", "apple", "cherry"]
print(sorted(words)) # capitals sort first
print(sorted(words, key=str.lower)) # case-insensitive
double = lambda x: x * 2
print(list(map(double, [1, 2, 3]))) # apply a function to every itemAny number of arguments: *args and **kwargs
Put * before a parameter name to collect any number of positional arguments into a tuple, and ** to collect any keyword arguments into a dictionary. You will mostly read these in other people's code (libraries use them a lot) rather than write them.
def average(*numbers):
return sum(numbers) / len(numbers)
print(average(4, 8))
print(average(1, 2, 3, 4, 5))
def describe(name, **details):
parts = [f"{key}={value}" for key, value in details.items()]
return name + ": " + ", ".join(parts)
print(describe("Sita", age=27, city="Brisbane"))
values = [3, 9, 6]
print(average(*values)) # * also unpacks a list into separate argumentsThe mutable default trap
Default values are created once, when the function is defined, not on every call. So a default list or dictionary is shared between calls, and things pile up in it. Use None as the default and create a new list inside.
def add_item_bad(item, basket=[]): # one list, shared by every call!
basket.append(item)
return basket
print(add_item_bad("apple"))
print(add_item_bad("pear")) # ['apple', 'pear']: surprise
def add_item(item, basket=None): # the safe pattern
if basket is None:
basket = []
basket.append(item)
return basket
print(add_item("apple"))
print(add_item("pear")) # ['pear']Recursion: a function that calls itself
A recursive function solves a problem by calling itself on a smaller version of the same problem. It needs two parts:
- a base case: a version so small the answer is obvious, which stops the recursion;
- a recursive case: do one small step, and call itself for the rest.
Example: the factorial 5! = 5 × 4 × 3 × 2 × 1. Notice that 5! = 5 × 4!, and 1! = 1. Without a base case the function calls itself forever, until Python stops it with a RecursionError. Recursion is natural for things that contain smaller things of the same kind: folders inside folders, comments with replies, decision trees in machine learning.
def factorial(n):
if n <= 1: # base case
return 1
return n * factorial(n - 1) # recursive case: a smaller problem
print(factorial(5)) # 120
def count_files(folder):
"""A folder is a dict: files are strings, sub-folders are dicts."""
total = 0
for name, item in folder.items():
if isinstance(item, dict):
total += count_files(item) # the same question for the sub-folder
else:
total += 1
return total
drive = {"cv.pdf": "", "photos": {"a.jpg": "", "b.jpg": "", "2025": {"c.jpg": ""}}, "notes.txt": ""}
print(count_files(drive)) # 5Watch recursion unwind
Step through factorial(3): each call waits for the smaller call to finish, then completes its own multiplication.
Interactive: this part runs in your browser.
Practice: check yourself
Write the code, then press ✔ Check my answer: hidden tests run your code and tell you exactly what is right. ▶ Run just shows the output. Stuck? Use a hint; the solution is there if you need it.
people is a list of (name, age) tuples. Set by_age to the list sorted by age (youngest first) and oldest to the name of the oldest person, using key=lambda ….
This function has the mutable default bug: calling it twice shares the list. Fix it so each call without a list starts with a new, empty one.
Write a recursive function total(n) that returns 1 + 2 + … + n (so total(4) is 10). Use a base case for n = 0.
Summary
Local variables live only inside a call; pass values in and return them out. Functions are values, so you can pass them as key to sorted, min and max, often as a lambda. Never use a list or dict as a default value. A recursive function needs a base case.
Key words
- scope
- the part of the program where a name can be used
- local variable
- created inside a function; gone when the call ends
- global variable
- created outside functions
- lambda
- a small unnamed function:
lambda x: x + 1 - key function
- a function that tells sorted/min/max what to compare
- *args / **kwargs
- collect any extra positional / keyword arguments
- recursion
- a function calling itself on a smaller problem
- base case
- the simple case that stops recursion
Common mistakes
- Expecting a variable created inside a function to exist outside it.
- Assigning to a global name inside a function and accidentally creating a local one instead.
def f(items=[]): the list is shared between calls. UseNone.sorted(people, key=p[1]): the key must be a function,key=lambda p: p[1].- A recursive function without a base case, or one that never gets closer to it: RecursionError.
Quiz
1. A variable created inside a function is…
2. What does sorted(["bb", "a", "ccc"], key=len) give?
3. What does lambda x: x ** 2 create?
4. Why is def f(items=[]) risky?
5. What stops a recursive function from calling itself forever?