Skip to main content

Functions

Functions

Complete lesson for Functions using LEARNCODEGURU’s 6-level learning model — from basics to advanced practice, with Python data structures and OOP where relevant.

L1

Basics — Functions

Section: Functions. Python functions — define, call, return, defaults, keyword args, *args/**kwargs, call by value vs reference, docstrings, and type hints.

What is a function?

  • A **function** is a named reusable block that takes inputs (parameters), runs statements, and may return a result.
  • Define with def name(params): and call with name(args).
  • **Real-life:** a juicer — fruit in, juice out; same machine, many uses.
PartMeaningExample
NameHow you call itadd
ParametersInput slots(a, b)
BodyIndented statementsreturn a + b
ReturnOutput value30
def add(a, b):
    return a + b

print(add(10, 20))
print(add("Hi, ", "Ada"))

return and None

  • return value exits immediately and sends value to the caller.
  • A function without return (or bare return) yields None.
  • You can return multiple values as a tuple: return x, y.
def greet(name):
    print(f"Hello, {name}")

def divmod_like(a, b):
    return a // b, a % b

result = greet("Ada")
print("greet returned:", result)
q, r = divmod_like(17, 5)
print(q, r)

Parameters vs arguments

  • **Parameters** are names in the def line; **arguments** are values supplied at the call site.
  • **Real-life:** parameter = blank on a form; argument = what you write in.
TermWhereExample
Parameterdef linedef tag(name, role):
ArgumentCall sitetag("Ada", "admin")
Positional argumentMatched by ordertag("Ada", "admin")
Keyword argumentMatched by nametag(role="admin", name="Ada")
def tag(name, role):
    return f"{name} [{role}]"

print(tag("Ada", "admin"))
print(tag(role="user", name="Bob"))

Positional and keyword arguments

  • Positional args fill parameters left-to-right. Keyword args use name=value and can be reordered.
  • In a call, all positionals must come **before** keywords.
  • Once you pass a parameter by keyword, later arguments for that call must also be keywords.
  • Keywords make long calls readable: send(to="a@b.com", retries=3) beats guessing order.
Call styleExampleNotes
All positionalarea(3, 4)Order matters
All keywordarea(height=4, width=3)Order free among keywords
Mixedarea(3, height=4)Positionals first
Invalid mixarea(width=3, 4)SyntaxError — positional after keyword
def area(width, height):
    return width * height

print(area(3, 4))
print(area(height=4, width=3))
print(area(3, height=4))

Default arguments

  • Give a parameter a default with =: def connect(host, port=5432). Callers may omit it.
  • Parameters with defaults must come **after** those without defaults: def f(a, b=1) OK; def f(a=1, b) SyntaxError.
  • Explicit arguments always override defaults.
  • Great for optional flags, ports, timeouts, and “usually this value” settings.
DefinitionCallBound values
def f(a, b=2)f(10)a=10, b=2
def f(a, b=2)f(10, 99)a=10, b=99
def f(a, b=2)f(10, b=7)a=10, b=7
def f(a=1, b=2)f()a=1, b=2
def f(a=1, b=2)f(b=9)a=1, b=9
def connect(host, port=5432, ssl=True):
    return {"host": host, "port": port, "ssl": ssl}

print(connect("localhost"))
print(connect("db.local", 3306, False))
print(connect("db.local", ssl=False))

Mutable default anti-pattern

  • Never write def f(xs=[]) or def f(d={}) — the mutable default is created **once** at definition time and shared across calls.
  • Safe idiom: def f(xs=None): then if xs is None: xs = [].
  • This is one of the most common Python interview traps.
PatternSafe?Why
def f(xs=[])NoSame list reused every call
def f(d={})NoSame dict reused every call
def f(xs=None) + create insideYesFresh object each call that needs it
def f(n=0, flag=False)YesImmutable defaults are fine
def bad_add(item, bucket=[]):
    bucket.append(item)
    return bucket

def good_add(item, bucket=None):
    if bucket is None:
        bucket = []
    bucket.append(item)
    return bucket

print(bad_add(1), bad_add(2))
print(good_add(1), good_add(2))

Variable-length positional arguments (*args)

  • *args collects extra **positional** arguments into a **tuple**.
  • The name args is convention; the * is required.
  • Useful for aggregators (total, print_all) and flexible wrappers.
  • Required parameters can appear before *args; keyword-only params can appear after.
DefinitionCallargs value
def f(*args)f()()
def f(*args)f(1, 2, 3)(1, 2, 3)
def f(label, *args)f("nums", 10, 20)label="nums", args=(10, 20)
def f(*args)f(*[1, 2])(1, 2) (unpack list into positionals)
def total(*nums):
    return sum(nums)

def show(label, *values):
    print(label, values)

print(total(1, 2, 3, 4))
print(total())
show("nums", 10, 20, 30)

Variable-length keyword arguments (**kwargs)

  • **kwargs collects extra **keyword** arguments into a **dict**.
  • The name kwargs is convention; the ** is required.
  • Common for config builders, optional named options, and decorator wrappers.
  • You cannot pass the same keyword twice in one call.
DefinitionCallkwargs value
def f(**kwargs)f(){}
def f(**kwargs)f(a=1, b=2){'a': 1, 'b': 2}
def f(name, **kwargs)f("Ada", city="Pune")name="Ada", kwargs has city
def f(**kwargs)f(**{"x": 1}){'x': 1} (unpack dict into keywords)
def build_profile(name, **fields):
    profile = {"name": name}
    profile.update(fields)
    return profile

print(build_profile("Ada", city="Pune", level=5))
print(build_profile("Bob"))

Combining defaults, *args, and **kwargs

  • Typical flexible signature: def f(a, b=1, *args, **kwargs).
  • Call unpacking: f(*list_or_tuple) fills positionals; f(**dict) fills keywords.
  • For the full ordering rules (positional-only /, keyword-only after *), see the **Function Arguments** lesson.
FeatureSyntaxCollects / means
Defaultb=1Optional parameter
Var positional*argsExtra positionals → tuple
Var keyword**kwargsExtra keywords → dict
Unpack sequencef(*items)Expand list/tuple into positionals
Unpack mappingf(**opts)Expand dict into keywords
def report(title, *lines, **meta):
    print("TITLE:", title)
    for line in lines:
        print("-", line)
    if meta:
        print("META:", meta)

report("Status", "OK", "Cached", level="info", code=200)

def volume(l, w, h):
    return l * w * h

print(volume(*[2, 3, 4]))
print(volume(**{"l": 2, "w": 3, "h": 5}))

Call by value vs call by reference

  • **Call by value** (classic): the callee gets a **copy** of the data. Changing the parameter does not affect the caller’s variable.
  • **Call by reference** (classic): the callee gets an **alias** to the caller’s variable. Reassignment and mutation both affect the caller.
  • Python is neither in the C/C++ sense. It uses **call by object reference** (also called pass-by-assignment / call by sharing): the parameter receives a **copy of the reference** to the same object.
  • **Immutable** args (int, float, str, tuple, bool, None): rebinding inside looks like call by value — the caller’s name is unchanged.
  • **Mutable** args (list, dict, set, custom objects): in-place mutation (append, pop, item assign) is visible to the caller — often compared to call by reference.
  • Rebinding the parameter (x = ...) **never** rebinds the caller’s name, whether the object is mutable or not.
IdeaWhat the callee getsCaller sees change?
Call by valueCopy of the valueNo (rebind or mutate copy)
Call by referenceAlias to caller’s variableYes (rebind and mutate)
Python (object reference)Copy of the referenceOnly if you **mutate** a shared mutable object
Python rebind x = newLocal name points elsewhereNo — caller’s name unchanged
Python mutate x.append(1)Same list objectYes — caller sees the mutation
# Looks like call by value (immutable int)
def bump(n):
    n = n + 10
    print("inside bump:", n)

x = 5
bump(x)
print("after bump:", x)  # still 5

# Mutation looks like call by reference (mutable list)
def add_item(items):
    items.append("Ada")
    print("inside add_item:", items)

names = ["Bob"]
add_item(names)
print("after add_item:", names)  # ["Bob", "Ada"]

# Rebinding a mutable parameter does NOT change the caller
def replace(items):
    items = ["Zoe"]  # local rebind only
    print("inside replace:", items)

data = ["Bob"]
replace(data)
print("after replace:", data)  # still ["Bob"]

Immutable vs mutable arguments in practice

  • To “change” an immutable for the caller, **return** the new value and assign: x = bump(x).
  • To update a mutable safely, either mutate deliberately or return a new copy — document which style you use.
  • Prefer returning new values for clarity; mutate only when performance or API design requires it.
  • id(obj) shows object identity — same id means the same object was shared.
TypeExampleTypical caller effect
Immutableint, str, tupleCallee rebind has no effect; return a new value
Mutablelist, dict, setIn-place methods affect caller’s object
Safe updatereturn x + 1Caller does x = f(x)
In-place updatelst.append(v)Caller’s list grows
Avoid surpriselst = lst + [v] insideRebind only — caller’s list unchanged
def next_score(score):
    return score + 1  # return new int

def mark_done(tasks, name):
    tasks.append(name)  # mutate shared list
    return tasks

s = 10
s = next_score(s)
print(s)

todo = ["read"]
mark_done(todo, "code")
print(todo)

a = [1, 2]
print("before id:", id(a))

def touch(xs):
    print("same object?", id(xs) == id(a))
    xs[0] = 99

touch(a)
print(a)

Docstrings and help

  • The first string in a function body is the **docstring** — use triple quotes.
  • Accessible via help(fn) or fn.__doc__.
  • Good docstrings state purpose, parameters, and return value briefly.
def area(radius):
    """Return area of a circle given radius."""
    return 3.14159 * radius * radius

print(area(5))
print(area.__doc__)

Type hints (annotations)

  • Hints document expected types: def f(x: int) -> str:.
  • They are not enforced at runtime by Python itself (tools like mypy check them).
  • Use list[int], dict[str, float] on 3.9+ (or from typing import ... on older).
def full_name(first: str, last: str) -> str:
    return f"{first} {last}"

def average(nums: list[float]) -> float:
    return sum(nums) / len(nums)

print(full_name("Ada", "Lovelace"))
print(average([10.0, 20.0, 30.0]))

Functions are objects

  • Functions are first-class: assign to variables, pass as arguments, store in lists.
  • Call through the new name the same way.
  • This enables callbacks and higher-order helpers (sorted(..., key=fn)).
def square(n):
    return n * n

op = square
ops = [square, abs]
print(op(6))
print([f(-4) for f in ops])

Side effects vs pure functions

  • **Pure:** same inputs → same output; no mutation of outside state.
  • **Side effects:** print, write files, mutate globals/inputs.
  • Prefer pure cores for logic; isolate I/O at the edges.
def pure_add(a, b):
    return a + b

def impure_append(bucket, item):
    bucket.append(item)
    return bucket

print(pure_add(2, 3))
data = [1]
print(impure_append(data, 2), data)

Early return and guard clauses

  • Return early for invalid inputs to keep the happy path flat.
  • Avoid deep nesting of if/else when guards suffice.
def normalize_score(score):
    if score is None:
        return 0
    if score < 0:
        return 0
    if score > 100:
        return 100
    return score

print([normalize_score(s) for s in [None, -5, 40, 150]])
L2

Advanced — Functions

LEGB reminder and nested defs

  • Name lookup: Local → Enclosing → Global → Built-in (LEGB).
  • Nested functions can read enclosing variables; assign with nonlocal to rebind them.
  • Inner functions are useful for tiny helpers scoped to one outer function.
def make_counter():
    count = 0
    def inc():
        nonlocal count
        count += 1
        return count
    return inc

c = make_counter()
print(c(), c(), c())

Returning callables and partial application

  • A function can return another function (closure factory).
  • functools.partial freezes some arguments for later calls.
from functools import partial

def power(base, exp):
    return base ** exp

square = partial(power, exp=2)
cube = partial(power, exp=3)
print(square(5), cube(3))

Annotations introspection

  • fn.__annotations__ holds parameter/return hints as a dict.
  • Useful for frameworks, validation layers, and docs generation.
def send(to: str, retries: int = 3) -> bool:
    return True

print(send.__annotations__)
print(send("a@b.com"))

Design tips for readable functions

  • One function ≈ one job; name with verbs (calculate_total, load_user).
  • Keep parameter lists short; use a dict/dataclass when options grow.
  • Prefer returning values over mutating many inputs silently.
def calculate_total(prices, tax_rate):
    subtotal = sum(prices)
    return subtotal * (1 + tax_rate)

print(round(calculate_total([100, 50], 0.18), 2))
L3

Tricky Interview Points

Q1) How do you define a function in Python?

Answer With def name(parameters): followed by an indented body. Call it with name(arguments).

Q2) What does a function return if there is no return statement?

Answer It returns None.

Q3) Parameters vs arguments?

Answer Parameters are the names in the function definition; arguments are the actual values passed when calling.

Q4) Positional vs keyword arguments?

Answer Positional match by order; keyword match by name (name=value). In a call, positionals must come before keywords.

Q5) What are default arguments?

Answer Parameters with = value that callers may omit. Defaults must follow non-default parameters in the definition.

Q6) Why is def f(xs=[]) dangerous?

Answer The mutable list default is created once at definition time and shared across calls, so later calls see previous appends. Use None and create a new list inside.

Q7) What is *args?

Answer A parameter that collects extra positional arguments into a tuple. Useful for variable-length inputs.

Q8) What is **kwargs?

Answer A parameter that collects extra keyword arguments into a dict. Useful for optional named options and wrappers.

Q9) How do you unpack a list/dict into a call?

Answer f(*sequence) expands positionals; f(**mapping) expands keywords whose keys match parameter names.

Q10) Is Python call by value or call by reference?

Answer Neither in the classic sense. Python uses call by object reference (pass-by-assignment): parameters get a copy of the reference to the same object. Mutation of mutables is visible to the caller; rebinding the parameter is not.

Q11) Why does changing an int inside a function not change the caller?

Answer Ints are immutable. n = n + 1 rebinds the local name to a new int object; the caller’s name still refers to the old int.

Q12) Why can a function change a caller’s list?

Answer The parameter and the caller’s variable refer to the same list object. In-place methods like append mutate that shared object.

Q13) Does items = [] inside a function clear the caller’s list?

Answer No. That rebinds only the local parameter. To clear the shared list use items.clear() or del items[:].

Q14) Are Python functions first-class objects?

Answer Yes. They can be assigned, passed as arguments, returned from other functions, and stored in data structures.

Q15) What is a docstring?

Answer A string literal as the first statement in a function (or class/module) describing its purpose; available via help() / __doc__.

Q16) Do type hints enforce types at runtime?

Answer No. They are optional annotations for humans and static checkers unless you add your own runtime validation.

Q17) What is a pure function?

Answer A function whose output depends only on its inputs and that has no observable side effects (no I/O, no mutating external state).

Q18) Can a function return multiple values?

Answer Syntactically yes via tuple packing: return a, b. The caller unpacks the tuple.

Q19) What is LEGB?

Answer Python’s name resolution order: Local, Enclosing, Global, Built-in.

Q20) Difference between print and return?

Answer print writes to the console (side effect). return sends a value to the caller for further use.

L4

Simple Programs

Temperature converter functions

def c_to_f(c):
    return c * 9 / 5 + 32

def f_to_c(f):
    return (f - 32) * 5 / 9

print(c_to_f(0), c_to_f(100))
print(round(f_to_c(98.6), 1))

Defaults + keyword calls

def power(base, exp=2):
    return base ** exp

print(power(5))
print(power(2, 10))
print(power(exp=3, base=4))

*args total and **kwargs profile

def total(*nums):
    return sum(nums)

def profile(name, **fields):
    return {"name": name, **fields}

print(total(1, 2, 3, 4))
print(profile("Ada", city="Pune", level=5))

Unpacking into a call

def volume(l, w, h):
    return l * w * h

print(volume(*[2, 3, 4]))
print(volume(**{"l": 2, "w": 3, "h": 5}))

Call by value vs reference demos

def try_rebind_int(n):
    n = 100

def try_mutate_list(xs):
    xs.append(99)

def try_rebind_list(xs):
    xs = [0]

a = 1
try_rebind_int(a)
print("int after rebind attempt:", a)

nums = [1, 2]
try_mutate_list(nums)
print("list after mutate:", nums)

vals = [1, 2]
try_rebind_list(vals)
print("list after rebind attempt:", vals)

Factorial and fibonacci helpers

def factorial(n):
    result = 1
    for i in range(2, n + 1):
        result *= i
    return result

def fib(n):
    a, b = 0, 1
    for _ in range(n):
        a, b = b, a + b
    return a

print(factorial(5), fib(10))

Pass function as callback

def apply_all(values, fn):
    return [fn(v) for v in values]

print(apply_all([1, 2, 3], lambda x: x * x))
print(apply_all(["ada", "bob"], str.upper))

Unpack returned pair

def min_max(nums):
    return min(nums), max(nums)

lo, hi = min_max([3, 9, 1, 7])
print(lo, hi)

Simple discount calculator

def final_price(amount, percent=0):
    if amount < 0 or percent < 0:
        raise ValueError("invalid")
    return round(amount * (1 - percent / 100), 2)

print(final_price(1000, 10))
print(final_price(250))
print(final_price(amount=500, percent=5))
L5

Problem Solving Tricks

  • Name functions as verbs; avoid vague names like doStuff.
  • Return early on invalid input to reduce nesting.
  • Prefer keyword args for boolean flags: save(path, *, overwrite=False) style (see Function Arguments lesson).
  • Never use mutable defaults ([], {}); use None + create inside.
  • *args is a tuple; **kwargs is a dict — treat them accordingly.
  • Unpack with * / ** when values already live in a list or dict.
  • Remember: Python passes object references — mutate mutables carefully; rebind never affects the caller.
  • To update an int/str for the caller, return the new value: x = f(x).
  • Use help(fn) in the REPL while learning stdlib callables.
  • callable(x) checks whether an object can be called.
  • Prefer returning data over printing inside core logic functions.
  • When a function grows past ~30 lines, split responsibilities.
L6

Practice Programs List

  1. Write is_palindrome(text) ignoring case and spaces.
  2. Implement clamp(n, lo=0, hi=100) with defaults and keyword calls.
  3. Write total(*nums) and call it with both separate args and *[...].
  4. Write config(name, **opts) that merges defaults with kwargs.
  5. Demonstrate the mutable-default bug, then fix it with None.
  6. Show call-by-value-like behavior with an int and call-by-reference-like mutation with a list.
  7. Prove that xs = [] inside a function does not clear the caller’s list; then clear it with .clear().
  8. Create pure mean / median helpers for a list of numbers.
  9. Write a function that returns both sum and average as a tuple.
  10. Add guard clauses to reject empty lists in a statistics helper.
  11. Use __annotations__ to print parameter types of your function.
  12. Build a nested helper function used only inside one outer function.
  13. Write unit-style asserts for three edge cases of a discount function.
  14. Continue with the Function Arguments lesson for /, *, and keyword-only params.