hayaliv / Hi! Python / Level 0
Functions
A function packages steps under a name, takes parameters, and hands back a value.
Think of it like this
A function is a kitchen recipe card. You give it ingredients (parameters), it follows the steps, and it hands you a dish (the return value). Some ingredients have a default amount that is used unless you say otherwise.
Where the analogy stops being true. In a kitchen you can use a leftover later, but a name made inside a function cannot be used outside it (the example shows a NameError).
What to know
- def defines a function, and the call gives values to its parameters.
- return sends a value back to the caller.
- If a function ends without return, it gives back None.
- A parameter can have a default value, used when the caller leaves it out.
- By default, names assigned inside a function are local to that function, as the NameError in the example shows.
- A default value is evaluated once, when def runs, not on each call.
Example
def draft_reply(label, name="there"):
if label == "meeting_request":
return f"Hi {name}, happy to meet."
elif label == "not_interested":
return f"Thanks {name}, I will not follow up."
def log(msg):
note = "log: " + msg
print(draft_reply("meeting_request", "Sam"))
print(draft_reply("not_interested"))
print(draft_reply("question"))
print(log("hi"))
try:
print(note)
except NameError:
print("note is local to log")
It prints:
Hi Sam, happy to meet.
Thanks there, I will not follow up.
None
None
note is local to log
Predict, then check
1. What does this print?
def f(x, y=10):
return x + y
print(f(1), f(1, 2))Show the answer
11 3f(1) uses the default y=10. f(1, 2) overrides it.
2. What does this print?
def f(x):
x * 2
print(f(4))Show the answer
NoneThere is no return, so the function gives back None. The product was computed and thrown away.
3. What does this print?
def add_tag(tag, tags=[]):
tags.append(tag)
return tags
print(add_tag("a"))
print(add_tag("b"))Show the answer
['a']
['a', 'b']The default list is created once and shared by every call that omits tags, so the second call sees the first call's item.
Try it
This add_tag shares one list between calls. Fix it so each call without tags starts with a new empty list. Use None as the default.
def add_tag(tag, tags=[]):
tags.append(tag)
return tags
Show a solution
def add_tag(tag, tags=None):
if tags is None:
tags = []
tags.append(tag)
return tagsCommon mistake
A mutable default such as tags=[] is created once, so calls share it. The third prediction above shows add_tag('a') then add_tag('b') giving ['a', 'b'] on the second call. A good habit is to default to None and build the list inside the function.
In a small-language-model project
In a fine-tuning project you usually wrap steps such as clean_reply or draft_reply in small functions so you can test each one on its own.
Sources
Each quote below appears word for word on the cited page of the official Python documentation (version 3.12).
The return statement returns with a value from a function.
docs.python.org/3.12/tutorial/controlflow.html — return sends a value back from a function.Falling off the end of a function also returns None .
docs.python.org/3.12/tutorial/controlflow.html — Falling off the end gives None.The execution of a function introduces a new symbol table used for the local variables of the function.
docs.python.org/3.12/tutorial/controlflow.html — A function call introduces a local symbol table.all variable assignments in a function store the value in the local symbol table
docs.python.org/3.12/tutorial/controlflow.html — Assignments inside a function store in the local symbol table.Important warning: The default value is evaluated only once.
docs.python.org/3.12/tutorial/controlflow.html — Default values are evaluated once.the expression is evaluated once, when the function is defined
docs.python.org/3.12/reference/compound_stmts.html — Defaults are evaluated when the function definition runs.