hayaliv

hayaliv / Hi! Python / Level 0

Functions

A function packages steps under a name, takes parameters, and hands back a value.

Hi! Python · Level 0: Python core · Checked against the Python 3.12 documentation · Updated 2026-10-17

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

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 3

f(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
None

There 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 tags

Common 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).

Step through this lesson in the Hi! Python desktop

← Control flowComprehensions →