1.2.27Introduction to Programming (Python)

Functions — def, parameters, return, docstrings

1,831 words8 min readdifficulty · medium1 backlinks

WHY do functions exist?

Three jobs a function does:

  1. Abstraction — hide how behind a name (area(r) instead of 3.14159*r*r).
  2. Reuse — call it anywhere, any number of times.
  3. Isolation — its inner variables live in their own scope, so they don't pollute the rest of your program.

WHAT is the anatomy? (Derivation from scratch)

Let's build a function piece by piece, asking "why this part?" at each step.

Step 1 — def name():

Why? Python needs a marker to know "store this block, don't run it yet." def creates a function object and binds it to name. Defining ≠ running.

def greet():
    print("Hi")

Nothing prints yet. Only greet() (with parentheses) calls it.

Step 2 — parameters (x, y)

Why? A machine with no inputs always does the same thing. Parameters let one definition serve infinitely many inputs.

def add(a, b):     # a, b are PARAMETERS (the placeholders)
    return a + b
 
add(2, 3)          # 2 and 3 are ARGUMENTS (the actual values)

Step 3 — return

Why? Without return, the work happens but the answer escapes into the void. return sends the result back so the caller can use it.

def square(n):
    return n * n
 
y = square(5)      # y is now 25

Step 4 — docstring

Why? Six months later you (or a teammate) ask "what does this do?" A docstring is documentation that lives inside the function and is readable via help().

def area(r):
    """Return the area of a circle of radius r."""
    return 3.141592653589793 * r * r

help(area) prints that line. It's the first string literal right under def.

Figure — Functions — def, parameters, return, docstrings

HOW does a call actually work? (Execution trace)


Parameter flavours


return details that bite


Flashcards

What keyword starts a function definition in Python?
def
What is the difference between a parameter and an argument?
Parameter is the placeholder name in the def line; argument is the actual value passed when calling.
What does a function return if it has no return statement?
None
Difference between print and return?
print displays text to the screen; return hands a value back to the caller for further use.
What is a docstring and how do you write one?
A string literal placed as the first line inside the function body, documenting what it does; readable via help().
What does return a, b return?
A tuple (a, b).
Why is def f(items=[]) dangerous?
The default list is created once and shared across calls, so it accumulates state between calls.
How do you give a parameter a default value?
Assign in the def line, e.g. def power(base, exp=2):.
What happens to code written after a return on the same path?
It never executes; return exits the function immediately.
Defining a function vs calling it?
def name(): ... only creates the function object; name() with parentheses actually runs it.

Recall Feynman: explain to a 12-year-old

A function is like a vending machine. You build it once and label it (def). You put coins in the slot (the arguments), the machine does its hidden work, and it drops out a snack (return). The slot names are the parameters. If you forget the return, the machine takes your coins and gives back nothing (None). The little sticker on the machine saying "this gives chips" is the docstring. Build the machine once, use it a thousand times.

Connections

  • Variables and Scope — parameters and locals live in the function's own scope.
  • Control Flow — if statements — used inside function bodies for branching returns.
  • Lists and Tuples — returning multiple values uses tuple packing/unpacking.
  • Recursion — a function that calls itself, built directly on def/return.
  • Lambda and Higher-order Functions — anonymous one-line functions.
  • DRY Principle — the design motivation for functions.

Concept Map

enables

provides

provides

provides

creates

declares

fill

hands value to caller

without return gives

documents

Function

DRY principle

Abstraction

Reuse

Isolation - scope

def keyword

Parameters - slots

Arguments - values

return

docstring

Returns None

Hinglish (regional understanding)

Intuition Hinglish mein samjho

Socho function ek vending machine hai. Ek baar def se machine bana lo, naam de do (jaise add), aur uske andar logic likh do. Phir jab bhi zaroorat ho, uss naam ko call karke kaam karwa lo — bar bar wahi code copy-paste karne ki zaroorat nahi. Yahi DRY principle hai: "Don't Repeat Yourself". Machine mein jo coin slots hote hain woh parameters hain, aur jo asli paise dalte ho woh arguments hain. Slot vs asli value — yeh difference yaad rakhna.

return ka matlab hai machine se snack bahar aana — yani value wapas caller ko milna. Bahut log print aur return ko same samajh lete hain. Galat! print sirf screen pe dikhata hai, par return actual value wapas deta hai jise aap y = square(5) mein store kar sakte ho. Agar function mein return nahi likha, to woh chupke se None return karta hai — aur tumhara aage ka maths toot jayega.

Docstring woh chhota sticker hai machine pe — """yeh kya karta hai""" — jise tum def ke turant neeche likhte ho. Baad mein help(function) se padh sakte ho. Aur ek classic trap: def f(items=[]) likhna. Lagta hai har call mein nayi list banegi, par actually woh ek hi list saari calls mein share hoti hai aur purana data yaad rakhti hai. Iska fix hai items=None use karna aur andar if items is None: items = []. Bas itna samajh lo, to functions tumhare poore programming ki backbone ban jayenge.

Go deeper — visual, from zero

Test yourself — Introduction to Programming (Python)

Connections