Functions, Part 2: Functions as Values
After this lesson, you will be able to:
- Follow a call from one function into another, and back out
- Read the call stack, and say why a local name disappears when a function returns
- Explain a closure: a function that remembers where it was made
- Pass a function to another function, and use functools helpers like lru_cache
#Functions Calling Functions
Functions can call other functions, building up complexity from simple pieces:
def is_positive(text):
"""Check if text contains positive words."""
positive_words = ["good", "great", "awesome", "love", "amazing", "excellent"]
for word in text.lower().split():
if word in positive_words:
return True
return False
def is_negative(text):
"""Check if text contains negative words."""
negative_words = ["bad", "terrible", "awful", "hate", "horrible", "worst"]
for word in text.lower().split():
if word in negative_words:
return True
return False
def classify_sentiment(text):
"""Classify text as positive, negative, or neutral."""
pos = is_positive(text)
neg = is_negative(text)
if pos and not neg:
return "positive"
elif neg and not pos:
return "negative"
elif pos and neg:
return "mixed"
else:
return "neutral"
# Test the pipeline
reviews = [
"This movie was great and amazing!",
"Terrible experience, the worst ever.",
"It was okay, nothing special.",
"I love the great food but hate the terrible service.",
]
for review in reviews:
sentiment = classify_sentiment(review)
print(f"[{sentiment:>8}] {review}")This pattern (small, focused functions composed into larger workflows) is how real programs are built. Each function does one thing well, and you chain them together.
#Interactive Visualization: Scope & Call Stack
Visualize Python's LEGB scope resolution, call stack frames, and closure variable capture:
#Watch frames stack and unwind
#LEGB: name lookup, animated
x, it searches four concentric scopes in a fixed order: Local → Enclosing → Global → Built-in. The first match wins; if none match, you get NameError. The visualizer below makes the search visible — a ball expands outward through the rings until it finds the binding, then snaps back to the call site with the value. Six presets cover every shape this lookup can take, including the nonlocal / global write-target rules.Build a tip calculator
Write a function `calculate_total(bill, tip_pct=15)` that returns the total amount to pay (bill + tip). The tip percentage should default to 15%. Then call it twice — once with default tip, once with a custom tip — and print both totals.
Total on $50 (default 15%): $57.50
Total on $80 (20% tip): $96.00#Key Takeaways
- Functions call other functions, and each call gets its own frame, so a small function used by three callers keeps no state between them. Build a workflow from focused pieces and each piece stays testable on its own.
- The call stack grows and unwinds — every active call is a frame stacked on the one that called it, and returning pops it off. This is why a traceback reads bottom-up and why runaway recursion eventually exhausts the stack.
- A name is found by the LEGB search — local, then enclosing, then global, then built-in. The first scope that has the name wins, and only if none of the four do you get a
NameError. - A closure remembers where it was defined — an inner function keeps access to its enclosing function's variables even after that function has returned, which is what makes a function factory possible.
- A closure captures the VARIABLE, not the value — functions built in a loop all see the loop variable's final value. Bind it with a default argument,
lambda i=i: i, when you want each one to remember its own. - Functions are objects you can pass around — store them in a dict, hand them to another function, return them from one.
functoolsthen addslru_cacheto memoise results andpartialto fix arguments in advance.
Can a function defined inside another function access the outer function's variables?
This loop builds three functions, one per value. Every one of them reports 2. Fix it so they report 0, 1 and 2.
[0, 1, 2]