Functions Deep Dive
Every chapter so far has quietly been building toward this one. Chapter 9 even wrote small, single-expression functions with lambda — but lambda can't hold a loop, an if block, or more than one line. This chapter introduces def: the real, full-powered way to name a reusable block of code, give it inputs, and get a result back. Once def is in your toolbox, everything from Chapter 1 onward can be organized into clean, reusable, testable pieces — which is exactly how real production code is structured.
How to read this chapter
- This chapter is unusually broad. Eight sub-topics instead of the usual six, because "functions" covers a lot of ground: definitions, defaults, variable-length arguments, scope, recursion, closures, and decorators.
- Each idea builds on the last. Scope (sub-topic 4) explains why closures (sub-topic 6) even need
nonlocal. Read them in order the first time through. - Functions are how real codebases stay maintainable. Nearly every example here is a small, reusable helper — the same shape you'll find in production code at any company.
1. Defining functions: def, parameters, return
def name(parameters):starts a function definition; the indented block underneath is its body.- Parameters are named inputs; calling the function with actual values fills them in.
returnhands a value back to whoever called the function — it's not the same thing asprint().
return. You've been calling built-in functions since
Chapter 1 — print(), len(),
range() — this chapter is about writing your own.
def greet(name):
return "Hello, " + name + "!"
message = greet("Priya")
print(message) # Hello, Priya!
Thought process: the smallest useful function demo needs one parameter, one line of real work, and a call site that proves the return value is usable — printing the raw call itself (print(greet("Priya"))) rather than a bare call is what makes "return hands a value back" observable instead of asserted.
Write the prompt you'd give an AI assistant to build this:
Show a strong version of this prompt
Write a Python function called greet(name) that takes one string parameter and returns (not prints) the string "Hello, " + name + "!". Then show it being called by storing the result in a variable called message and printing that variable, so it's clear the function hands back a real value rather than printing anything itself.
def greet(name): defines the function — it doesn't run
anything yet. The body only runs when greet("Priya")
actually calls it, with "Priya" filling
in the name parameter for that one call.
name in def greet(name):. An
argument is the actual value passed in when calling
it — "Priya" in greet("Priya"). People often
use the words interchangeably, but the definition side is the
parameter and the call side is the argument.
return is easy to confuse with print() at
first, because both can make a value show up on screen. They do
completely different jobs:
def add_printing(a, b):
print(a + b) # shows the result, hands nothing back
def add_returning(a, b):
return a + b # hands the result back to the caller
add_printing(3, 4) # prints 7
result = add_returning(3, 4)
print(result * 10) # 70 — only possible because a value came back
Thought process: the point isn't the addition itself, it's contrasting two functions side by side that do the same math but differ in exactly one line — one prints, one returns — so the difference in what the caller can do afterward (multiply the result by 10) becomes concrete proof, not just a stated rule.
Write the prompt you'd give an AI assistant to build this:
Show a strong version of this prompt
Write two Python functions, add_printing(a, b) and add_returning(a, b), that both compute a + b. add_printing should only print the sum and return nothing; add_returning should return the sum without printing it. Then demonstrate the practical difference: call add_printing(3, 4) directly, then call result = add_returning(3, 4) and print(result * 10) — showing that only the returned value can be reused in further computation.
add_printing's result disappears the moment it's shown —
there's nothing to store or reuse. add_returning hands
its result back as a real value, so it can be stored in a variable,
passed to another function, or used in more math. Most functions you
write should return a value rather than just printing
it, so the caller decides what to do with the result.
A function with no return statement at all doesn't
error — it just hands back a special value, None,
automatically:
def log_message(text):
print("LOG:", text)
# no return statement
outcome = log_message("server started")
print(outcome) # None
Thought process: the demo has to actually capture and print the "missing" return value — printing outcome after the call is what turns "a function with no return gives back None" from a claim into something the reader watches happen.
Write the prompt you'd give an AI assistant to build this:
Show a strong version of this prompt
Write a Python function called log_message(text) that only prints "LOG:" followed by text, with no return statement at all. Then call it as outcome = log_message("server started") and print(outcome), so it's visible that a function with no explicit return implicitly hands back None.None?
None is Python's built-in value meaning "no value here."
Any function without an explicit return — or with a bare
return and nothing after it — automatically hands back
None when it's called.
Go Deeper: return also exits the function immediately
The moment a return statement runs, the function
stops — any code after it in that same call never executes. This
makes return useful for early-exit checks, like
returning immediately if an input is invalid, without needing an
else block to skip the rest of the function.
def name(parameters):defines a function; nothing runs until it's called.returnhands a value back to the caller;print()only displays a value and hands nothing back.- A function with no
returnstatement implicitly returnsNone.
2. Default arguments
- A parameter can have a default value, used automatically when the caller doesn't provide one.
- Calling the function still lets you override the default by passing a value explicitly.
- A mutable default (like a list) is a well-known trap — it's shared across every call, not recreated each time.
def greet(name, greeting="Hello"):
— used automatically whenever the caller doesn't supply that
argument themselves.
def greet(name, greeting="Hello"):
return greeting + ", " + name + "!"
print(greet("Priya")) # Hello, Priya!
print(greet("Amir", "Welcome")) # Welcome, Amir!
greet("Priya") uses the default "Hello"
since no second argument was given. greet("Amir",
"Welcome") overrides it — the value passed in always wins over
the default.
There's a trap worth knowing before you ever use a list or dictionary as a default value. Python creates default values once, when the function is defined — not fresh on every call — so a mutable default gets shared and quietly accumulates across calls:
def add_item(item, cart=[]):
cart.append(item)
return cart
print(add_item("apple")) # ['apple']
print(add_item("banana")) # ['apple', 'banana'] — NOT a fresh empty cart!
cart=[] is created ONE time, when add_item is defined
call 1: add_item("apple") -> appends to that same list -> ['apple']
call 2: add_item("banana") -> appends to that SAME list -> ['apple', 'banana']
Every call that doesn't pass its own cart shares the one list from Line 1.
The fix is a well-known pattern: default the parameter to
None, then create a brand-new list inside the function
body if none was given. This way, every call that doesn't pass its
own list gets its own fresh one:
def add_item(item, cart=None):
if cart is None:
cart = []
cart.append(item)
return cart
print(add_item("apple")) # ['apple']
print(add_item("banana")) # ['banana'] — fresh list every time
Go Deeper: default arguments must come after non-default ones
def greet(greeting="Hello", name): is a
SyntaxError — once a parameter has a default, every
parameter after it must also have one. Python needs to be able to
tell, just from position, which arguments a caller intended to
skip.
- A default argument,
param=value, is used automatically when the caller doesn't supply that argument. - Passing a value explicitly always overrides the default.
- Never use a mutable default like
[]or{}— it's created once and shared across every call; default toNoneand create the mutable value inside the function instead.
3. *args and **kwargs
*argscollects any number of extra positional arguments into a tuple.**kwargscollects any number of extra keyword arguments into a dictionary.- Both exist for when the number of arguments genuinely can't be known in advance — not as a default way to write every function.
*args?
*args in a function definition collects any number of
extra positional arguments into a single tuple named
args. The * is what does the collecting —
args itself is just a conventional name.
def total(*args):
return sum(args)
print(total(1, 2, 3)) # 6
print(total(10, 20)) # 30
print(total()) # 0
total works with any number of arguments — one, two,
ten, or zero — because *args gathers whatever was passed
into a tuple, and sum() (Chapter 7) adds up whatever's
inside it.
**kwargs?
**kwargs collects any number of extra keyword arguments
— arguments passed as name=value — into a single
dictionary named kwargs. Like *args, the
double ** is what matters; kwargs is just
the conventional name.
def build_profile(name, **kwargs):
profile = {"name": name}
profile.update(kwargs)
return profile
print(build_profile("Zoe", age=29, city="Austin"))
# {'name': 'Zoe', 'age': 29, 'city': 'Austin'}
build_profile always needs name, but any
other detail — age, city, job title, anything — gets collected into
kwargs without the function needing a parameter for
every possible field in advance.
Go Deeper: genuinely useful vs. over-engineering
*args and **kwargs earn their keep when a
function truly can't know its argument count ahead of time — a
total() that adds any number of values, or a logging
wrapper (Sub-topic 7) that needs to forward whatever arguments the
wrapped function receives. Reaching for them on a function that
always takes the same two or three named things just hides what
the function actually expects — plain, named parameters are more
readable whenever the shape of the input is already known.
*argscollects extra positional arguments into a tuple.**kwargscollects extra keyword arguments into a dictionary.- Use both only when a function genuinely needs a variable number of arguments — named parameters are clearer when the inputs are already known.
4. Variable scope: local, global, and nonlocal
- A variable created inside a function is local — it only exists while that function is running.
- A function can read a global variable, but assigning to a same-named variable creates a new local one instead of changing it.
- The
globalkeyword explicitly opts in to changing a global variable from inside a function.
def calculate_area(width, height):
area = width * height # local to this function
return area
print(calculate_area(4, 5)) # 20
# print(area) here would raise NameError — area doesn't exist out here
A function can freely read a variable defined outside it — that's normal and safe. The surprise shows up the moment a function tries to assign to a same-named variable: Python treats that as creating a brand-new local variable, not changing the outer one:
x = 10
def try_change():
x = 20 # creates a NEW local x, doesn't touch the outer one
return x
print(try_change()) # 20 — the local x
print(x) # 10 — the outer x, unchanged
This is a deliberate safety feature, not a limitation. Without it, any function anywhere in a large program could silently overwrite a variable another part of the program depends on, just by happening to reuse the same name.
Sometimes a function genuinely does need to change a variable
defined outside it — a running total updated by several different
calls, for example. The global keyword explicitly opts
in to that, telling Python "don't create a local — use the outer
one":
visit_count = 0
def record_visit():
global visit_count
visit_count += 1
record_visit()
record_visit()
record_visit()
print(visit_count) # 3
global keyword?
global name, written as the first line inside a
function body, tells Python that assignments to name in
this function should change the module-level (outer) variable,
instead of creating a new local one.
Go Deeper: nonlocal is global's cousin for nested functions
global reaches out to module-level variables from
inside a function. A different keyword, nonlocal,
does the same job one level in — letting a function defined
inside another function modify a variable from that
enclosing function, rather than the whole module. That situation —
a function nested inside another function — is exactly what
Sub-topic 6, closures, covers next, where nonlocal
gets used for real.
- A variable created inside a function is local — it exists only while that function runs.
- Assigning to a variable inside a function creates a new local one by default, even if an outer variable shares the name — this keeps functions from accidentally clobbering each other's variables.
global nameexplicitly opts in to changing a module-level variable from inside a function;nonlocaldoes the equivalent for a variable one function-level up, covered in Sub-topic 6.
5. Recursive functions
- A recursive function calls itself, working on a smaller version of the same problem each time.
- Every recursive function needs a base case — a condition where it stops calling itself.
- Recursion is elegant for naturally nested problems, but a plain loop is usually simpler and safer for everyday tasks.
A factorial is a classic recursive example — 4! = 4 × 3!,
and 3! = 3 × 2!, all the way down to 1! = 1,
which is the base case that stops the chain:
def factorial(n):
if n == 0 or n == 1:
return 1 # base case — stops the recursion
return n * factorial(n - 1) # recursive case
print(factorial(4)) # 24
Tracing factorial(4) shows each call waiting on a
smaller call before it can finish, then unwinding back out once the
base case is hit:
factorial(4) called
factorial(3) called
factorial(2) called
factorial(1) called
-> base case, returns 1
-> factorial(2) returns 2
-> factorial(3) returns 6
-> factorial(4) returns 24
That error is worth seeing once, so it's recognizable later —
forgetting the base case (or writing one that's never actually
reached) causes a RecursionError, because Python keeps
every waiting call in memory until one of them finally returns:
def countdown_broken(n):
print(n)
return countdown_broken(n - 1) # no base case — never stops
# countdown_broken(5) eventually raises:
# RecursionError: maximum recursion depth exceeded
Go Deeper: when a loop is simply the better tool
Every recursive function has a loop-based equivalent, and for
something like a factorial or a simple countdown, the loop version
is usually easier to read and uses a fixed, small amount of memory
regardless of the input size. Recursion earns its place on
problems that are naturally nested — walking a folder tree,
exploring a tree-shaped data structure — where "process this, then
recursively process the smaller pieces inside it" mirrors the
problem's actual shape. For everything else, honestly ask whether
a for or while loop would just be
simpler; Python's default recursion limit (around 1,000 calls deep)
also means recursion isn't safe for problems that could go
thousands of levels deep.
- A recursive function calls itself on a smaller version of the same problem.
- Every recursive function needs a base case — the condition where it stops calling itself and returns directly.
- Recursion suits naturally nested problems; a loop is usually simpler, uses less memory, and avoids Python's recursion depth limit for everyday tasks.
6. Closures
- A closure is a function defined inside another function that remembers variables from the outer function's scope.
- The outer function's variables stay alive for the inner function to use, even after the outer function has already returned.
nonlocallets the inner function modify — not just read — a captured outer variable.
A counter-maker is the classic motivating example — each call to
make_counter() builds a brand-new increment
function, and each one remembers its own separate
count:
def make_counter():
count = 0
def increment():
nonlocal count
count += 1
return count
return increment
counter = make_counter()
print(counter()) # 1
print(counter()) # 2
print(counter()) # 3
Without nonlocal, count += 1 inside
increment would create a brand-new local
count inside increment itself — the exact
"assignment creates a local" rule from Sub-topic 4, just one function
level deeper. nonlocal count tells Python to reuse and
modify the count that belongs to the enclosing
make_counter instead.
Calling make_counter() a second time proves each closure
keeps its own independent copy — a fresh count, separate
from the first counter's:
c1 = make_counter()
c1() -> 1
c1() -> 2
c1() -> 3
c2 = make_counter()
c2() -> 1 # a brand-new count, unrelated to c1's
A multiplier-maker is another common shape — the outer function's parameter, not just a local variable, gets remembered too:
def multiplier_maker(factor):
def multiply(n):
return n * factor # remembers factor from the enclosing call
return multiply
double = multiplier_maker(2)
triple = multiplier_maker(3)
print(double(5)) # 10
print(triple(5)) # 15
double and triple are both built from the
exact same multiply function definition, but each
remembers a different factor from the call that created
it — that's the whole point of a closure: the same inner logic,
customized by whatever it captured on the way out.
Go Deeper: only variables actually used inside the inner function get captured
A closure doesn't remember the entire outer function — only the
specific variables the inner function actually references. If
make_counter had ten unrelated local variables but
increment only ever used count, only
count would be captured; the rest are cleaned up
normally once make_counter finishes running.
- A closure is a function defined inside another function that remembers its enclosing scope's variables.
- Each call to the outer function creates a new, independent closure with its own captured variables.
nonlocalis required to modify — not just read — a captured variable from the enclosing function.
7. Decorators
- A decorator is a function that wraps another function, adding behavior before and/or after it runs.
@decorator_nameabove a function definition applies the decorator automatically.- Decorators lean directly on closures: the wrapper function remembers the original function it's wrapping.
Building one from scratch shows exactly how the pieces fit together — a decorator is really just a closure where the captured variable happens to be another function:
def log_calls(func):
def wrapper(*args, **kwargs):
print("Calling", func.__name__)
result = func(*args, **kwargs)
print(func.__name__, "returned", result)
return result
return wrapper
def add(a, b):
return a + b
logged_add = log_calls(add) # wrap add manually
print(logged_add(3, 4))
Calling add
add returned 7
7
wrapper uses *args and **kwargs
(Sub-topic 3) so it can forward any arguments straight
through to whatever function it's wrapping, no matter how many that
function takes. Writing logged_add = log_calls(add)
every time gets repetitive — Python's @ syntax applies
the exact same wrapping automatically, right at the point where the
function is defined:
def log_calls(func):
def wrapper(*args, **kwargs):
print("Calling", func.__name__)
result = func(*args, **kwargs)
print(func.__name__, "returned", result)
return result
return wrapper
@log_calls
def add(a, b):
return a + b
print(add(3, 4)) # same output as before — @log_calls did the wrapping
@ syntax?
@decorator_name, written directly above a function
definition, is shorthand for add = decorator_name(add)
— Python applies the decorator to the function immediately after
it's defined, so every call to add from then on actually
calls the wrapped version.
Timing how long a function takes is another common real use for a
decorator — the wrapping logic lives in exactly one place, and any
function can opt in just by adding @time_it above it:
def time_it(func):
def wrapper(*args, **kwargs):
start = 100.0 # a stand-in "clock reading" for this example
result = func(*args, **kwargs)
end = 100.2
print(func.__name__, "took", round(end - start, 2), "seconds")
return result
return wrapper
@time_it
def slow_add(a, b):
return a + b
print(slow_add(2, 2))
Go Deeper: real-world decorators usually add functools.wraps
Production decorators almost always add one more line,
@functools.wraps(func) above wrapper,
which preserves the original function's name and docstring instead
of replacing them with wrapper's. That needs
import functools, which is a Chapter 11 topic — worth
knowing it exists, but skipped here since this chapter doesn't use
import yet. The hand-written decorators above work
correctly without it; they just report func.__name__
slightly less precisely in edge cases.
- A decorator is a function that wraps another function to add behavior before, after, or around its call.
@decorator_nameabove a function definition is shorthand for reassigning the function to its wrapped version.- A decorator's wrapper typically uses
*args, **kwargsto forward any arguments through to the original function unchanged.
8. Real-world functions in production
- A small library of focused helper functions is how real, maintainable codebases are organized.
- Each function does one job and has a name that says exactly what that job is.
- Breaking logic into functions makes it testable, reusable, and easy for someone else to read later.
A signup form needs several independent checks — is the email shaped correctly, is the age a sensible number, is the password long enough. Writing each check as its own small function makes the whole validation step easy to read at a glance, and easy to test one rule at a time:
def is_valid_email(email):
return "@" in email and "." in email
def is_valid_age(age_text):
return age_text.isdigit() and 0 < int(age_text) < 120
def is_valid_password(password):
return len(password) >= 8
def validate_signup(email, age_text, password):
return (
is_valid_email(email)
and is_valid_age(age_text)
and is_valid_password(password)
)
print(validate_signup("zoe@example.com", "29", "supersecret")) # True
print(validate_signup("not-an-email", "29", "supersecret")) # False
validate_signup reads almost like plain English, because
each individual rule already has a name. If the password rule ever
needs to change — say, requiring a number too — only
is_valid_password needs updating, and every place that
calls it picks up the new rule automatically.
A small library of calculation helpers follows the same pattern — each function handles one computation, and a higher-level function combines them:
def calculate_subtotal(prices):
return sum(prices)
def calculate_tax(subtotal, rate=0.08):
return round(subtotal * rate, 2)
def calculate_total(prices, tax_rate=0.08):
subtotal = calculate_subtotal(prices)
tax = calculate_tax(subtotal, tax_rate)
return round(subtotal + tax, 2)
cart = [19.99, 5.00, 42.50]
print(calculate_total(cart)) # 72.4
Go Deeper: this is exactly what "breaking a problem down" means
Every function in this section could be inlined into one giant block of code that does the same job — but that version would be far harder to read, test, or fix. Real production codebases are built almost entirely from small, well-named functions like these, each one calling others, which is exactly why this chapter has spent so much time on how to define, scope, and wrap them correctly.
- Real codebases are organized as many small, focused functions rather than one long script.
- Each function should do one job and have a name that describes exactly what that job is.
- Small helper functions make validation and calculation logic easy to read, reuse, and fix in one place.
- Web frameworks and libraries are built almost entirely of functions calling other functions — a "route handler" in a web app is just a function Python calls automatically when a request comes in.
- Decorators power real production features like Flask's
@app.route()and pytest's@pytest.fixture— the exact wrapping pattern built by hand in Sub-topic 7, just applied to bigger jobs. - Closures are what make factory functions and configurable callbacks work throughout real libraries — one function shape, customized differently depending on what it captured when it was created.
Points to Remember
def name(parameters):defines a reusable function;returnhands a value back to the caller, while a function with noreturnimplicitly returnsNone.- A default argument (
param=value) is used when the caller omits that argument — but never default to a mutable value like[], since it's created once and shared across every call. *argscollects extra positional arguments into a tuple, and**kwargscollects extra keyword arguments into a dictionary — useful when a function genuinely needs a variable number of inputs.- A variable assigned inside a function is local by default, even if an outer variable shares its name;
globalexplicitly opts in to changing a module-level variable from inside a function. - A recursive function calls itself on a smaller version of the same problem until a base case stops it — useful for naturally nested problems, but a loop is usually simpler and safer for everyday tasks.
- A closure is a function defined inside another function that remembers its enclosing scope's variables;
nonlocallets it modify — not just read — a captured variable. - A decorator wraps another function to add behavior around it, applied automatically with
@decorator_name— and is really just a closure whose captured variable happens to be a function. - Real, maintainable codebases are built from many small, well-named functions, each doing one job, calling each other to build up bigger behavior.