🐍 Python for Everyone

← Back to all chapters

Chapter 10 of 27 Intermediate 50 min read

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

Copy-pasting the same five lines of code into three different places in a program is one of the most reliable ways to create a bug — fix it in one spot, forget the other two, and now the program behaves inconsistently. A function solves this by giving that block of code a name, a set of inputs, and a single place it lives. Every real Python program, from a ten-line script to a production web service, is built almost entirely out of functions calling other functions.
Sub-topic 1 of 8

1. Defining functions: def, parameters, return

At a glance
  • 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.
  • return hands a value back to whoever called the function — it's not the same thing as print().
Use this when: you're about to write the same logic more than once, or a chunk of code deserves its own name to make the program easier to read.
What is... a function? A function is a named, reusable block of code that runs when you call it by name. It can accept inputs (parameters), do some work, and optionally hand a result back with return. You've been calling built-in functions since Chapter 1 — print(), len(), range() — this chapter is about writing your own.
first_function.py
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.

What is... a parameter, versus an argument? A parameter is the name listed in the function's definition — 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:

return_vs_print.py
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:

implicit_none.py
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.
What is... 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.
try_function_basics.py
Click "Run Code" — try adding a second parameter and using it in the return.
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.

Quick recap
  • def name(parameters): defines a function; nothing runs until it's called.
  • return hands a value back to the caller; print() only displays a value and hands nothing back.
  • A function with no return statement implicitly returns None.
Sub-topic 2 of 8

2. Default arguments

At a glance
  • 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.
Use this when: a parameter has an obvious, sensible value most callers will want, but should still be changeable when needed.
What is... a default argument? A default argument is a value assigned to a parameter right in the function definition — def greet(name, greeting="Hello"): — used automatically whenever the caller doesn't supply that argument themselves.
default_argument.py
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:

mutable_default_trap.py
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!
why this happens — the default list is created once, not per call
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:

mutable_default_fixed.py
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
try_default_arguments.py
Click "Run Code" — try calling make_coffee() with only extra_shot set.
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.

Quick recap
  • 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 to None and create the mutable value inside the function instead.
Sub-topic 3 of 8

3. *args and **kwargs

At a glance
  • *args collects any number of extra positional arguments into a tuple.
  • **kwargs collects 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.
Use this when: a function truly needs to accept a variable number of inputs — not as a shortcut to avoid naming parameters clearly.
What is... *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.
using_args.py
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.

What is... **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.
using_kwargs.py
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.

try_args_kwargs.py
Click "Run Code" — try adding a third topping and a fourth detail.
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.

Quick recap
  • *args collects extra positional arguments into a tuple.
  • **kwargs collects 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.
Sub-topic 4 of 8

4. Variable scope: local, global, and nonlocal

At a glance
  • 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 global keyword explicitly opts in to changing a global variable from inside a function.
Why this matters: scope is what keeps one function's variables from accidentally clobbering another function's, or the rest of the program's.
What is... scope? Scope is the region of code where a variable name is visible and usable. A variable created inside a function only exists in that function's local scope — it disappears once the function finishes running, and code outside the function can't see it at all.
local_scope.py
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:

assignment_creates_local.py
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":

the_global_keyword.py
visit_count = 0

def record_visit():
    global visit_count
    visit_count += 1

record_visit()
record_visit()
record_visit()
print(visit_count)   # 3
What is... the 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.
try_scope.py
Click "Run Code" — try removing the global line and see what breaks.
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.

Quick recap
  • 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 name explicitly opts in to changing a module-level variable from inside a function; nonlocal does the equivalent for a variable one function-level up, covered in Sub-topic 6.
Sub-topic 5 of 8

5. Recursive functions

At a glance
  • 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.
Use this when: a problem is naturally defined in terms of a smaller version of itself, like a factorial, a nested folder structure, or a tree.
What is... recursion? Recursion is when a function calls itself, each time working on a smaller piece of the original problem, until it reaches a base case simple enough to answer directly without calling itself again.

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:

factorial_recursive.py
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) traced — calls going in, results coming back out
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
What is... a base case? A base case is the condition in a recursive function that returns an answer directly, without calling the function again. Without one, a recursive function calls itself forever, until Python runs out of room and raises an error.

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:

missing_base_case.py
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
try_recursion.py
Click "Run Code" — try changing the starting number.
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.

Quick recap
  • 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.
Sub-topic 6 of 8

6. Closures

At a glance
  • 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.
  • nonlocal lets the inner function modify — not just read — a captured outer variable.
Use this when: you need to create several independent functions that each remember their own separate piece of state.
What is... a closure? A closure is a function defined inside another function that "remembers" the enclosing function's variables, even after the outer function has finished running. The inner function carries its enclosing scope along with it, like a small backpack of remembered values.

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:

counter_maker.py
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:

two counters, each remembering its own separate count
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:

multiplier_maker.py
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.

try_closures.py
Click "Run Code" — try making a third greeter with a different greeting.
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.

Quick recap
  • 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.
  • nonlocal is required to modify — not just read — a captured variable from the enclosing function.
Sub-topic 7 of 8

7. Decorators

At a glance
  • A decorator is a function that wraps another function, adding behavior before and/or after it runs.
  • @decorator_name above a function definition applies the decorator automatically.
  • Decorators lean directly on closures: the wrapper function remembers the original function it's wrapping.
Use this when: the same extra behavior — timing, logging, checking something — needs to wrap several different functions without repeating that logic inside each one.
What is... a decorator? A decorator is a function that takes another function as input, defines a new function that adds some behavior around it, and returns that new function — effectively "wrapping" the original without changing its actual code.

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:

decorator_by_hand.py
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))
what actually happens when logged_add(3, 4) runs
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:

the_at_syntax.py
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
What is... the @ 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:

timing_decorator.py
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))
try_decorators.py
Click "Run Code" — try stacking a second decorator on top of @shout.
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.

Quick recap
  • A decorator is a function that wraps another function to add behavior before, after, or around its call.
  • @decorator_name above a function definition is shorthand for reassigning the function to its wrapped version.
  • A decorator's wrapper typically uses *args, **kwargs to forward any arguments through to the original function unchanged.
Sub-topic 8 of 8

8. Real-world functions in production

At a glance
  • 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.
Pattern to remember: a big program isn't one long script — it's many small functions, each solving one small piece, calling each other.

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:

validation_helpers.py
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:

calculation_helpers.py
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
What is... a helper function? A helper function is a small function that exists to support a larger one — it does one focused job (like computing tax) so the bigger function (like computing a total) can stay short and read like a summary of its steps, instead of one long block of math.
try_bringing_together.py
Click "Run Code" — try adding a third helper, like is_valid_domain.
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.

Quick recap
  • 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.
In the Real World

Points to Remember

← All Chapters Take the Quiz →