Python Functions
Create reusable blocks of code with def, arguments, defaults, and return values.
Why it matters: Chunking, prompt building, scoring, and metric helpers are all functions you can test and reuse.
Basics
Creating a Function
A function is a block of code that only runs when you call it.
Use def to define it. Put parameters in parentheses. Use return to send a value back.
If you do not return anything, the function returns None.
Common mistake: forgetting parentheses when you call the function.
Tiny example
Define a function, call it, print the result.
def greet(name):
return "hello " + name
print(greet("model"))Basics
Arguments and Defaults
You can give parameters default values. Callers may skip them.
Keyword arguments make calls readable: score("rag", threshold=0.5).
Never use a mutable default like []. Use None and create the list inside the function.
Common mistake: def f(items=[]) shares one list across every call.
Tiny example
Pass a keyword argument so the option is clear.
def score(text, threshold=0.7):
return len(text) > 3
print(score("rag", threshold=0.5))Basics
Return Multiple Values
Names created inside a function are local. They disappear when the function ends.
Return several values as a tuple: return mean, worst. Unpack on the call side.
For more than two or three values, prefer a dict so the meaning stays clear.
Tiny example
Return two values, then unpack them.
def stats(scores):
return sum(scores) / len(scores), min(scores)
mean, worst = stats([0.9, 0.7])
print(mean, worst)Then AI / ML
AI / ML examples
Same idea, used in real AI work. Press Try in lab to run it.
AI / ML example
AI / ML: build a prompt
Defaults keep the call site short and clear.
In AI / ML: GenAI code wraps system and user text in small builder functions.
example.py
Python
def build_prompt(question, style="concise"):
return f"Answer in a {style} style.\nQuestion: {question}"
print(build_prompt("What is RAG?"))
print(build_prompt("What is RAG?", style="detailed"))AI / ML example 2
AI / ML: mutable default trap
The broken version grows across calls. The fixed one does not.
In AI / ML: Message histories and bucket collectors must not use [] as a default.
example.py
Python
def broken(item, bucket=[]):
bucket.append(item)
return bucket
def fixed(item, bucket=None):
if bucket is None:
bucket = []
bucket.append(item)
return bucket
print(broken("a"), broken("b"))
print(fixed("a"), fixed("b"))Takeaways
- 1def creates a function; return sends a value back.
- 2Use keyword arguments for options; never use a mutable default.
- 3Return a tuple for two values, or a dict when names matter.