g↗genai/ learner
Python for AI / Lesson 09

Functions

A function is a named block of code that does one job. You write it once with def, then call it by name whenever you need the job done.

Concept + interactive labBeginner friendly

Functions: Name a job and reuse it.

Each term is defined where it first appears, in this order:

  1. Function: a named block of code that does one job.
  2. def: the keyword that stores a function under a name. A def line does not run the function.
  3. Call: a line such as make_title("Pasta") that runs the function.
  4. Parameter: a name in the def line that receives a value, such as topic.
  5. Argument: a value passed in a call, such as "Pasta".
  6. Default value: a value written in the def line, such as prefix="Chat", that is used when a call leaves that argument out.
  7. return: a line that hands a value back to the code that made the call.
  8. Docstring: a string used as the first statement in a function's body, which describes the function.
Running example (invented, text only)

This function joins a prefix, a colon and a topic. The prefix default and the separator : are made up for this lesson.

def make_title(topic, prefix="Chat"):
    return prefix + ": " + topic

def stores the function. A call runs it.

Python reads a def line and keeps the function under its name. The body, the indented lines, does not run then. When this block runs as a script file, it prints nothing.

def make_title(topic, prefix="Chat"):
    return prefix + ": " + topic

A call such as make_title("Pasta") runs the body. The result is handed back, which the return section explains. In this script the call does not show the result, so nothing appears on screen.

Diagram showing that def make_title stores the function without running its body, while calling make_title("Pasta") runs it and returns "Chat: Pasta". It also notes that the result is not printed automatically.
Writing def stores the function. The call is the step that runs the body.

Everyday analogy: a recipe card in a drawer. Writing the card does not cook anything. Cooking starts when someone follows it.

Parameters and arguments.

A parameter is a name in the def line. An argument is the value you pass in the call. Each argument fills a parameter. A parameter with a default can be left out of the call.

  • In def make_title(topic, prefix="Chat"), topic and prefix are parameters.
  • In make_title("Pasta"), "Pasta" is an argument. It fills topic.
  • An argument can also name its parameter, as in make_title("Pasta", prefix="Note"). That call fills prefix with "Note".

A default fills the gap.

A parameter written as prefix="Chat" has a default value. If the call leaves that argument out, Python uses the default. If the call passes a value, the passed value is used for that call only.

make_title("Pasta")              # prefix is "Chat"
make_title("Pasta", "Recipe")    # prefix is "Recipe"
Diagram comparing make_title("Pasta"), which uses the default prefix Chat and returns Chat: Pasta, with make_title("Pasta", "Recipe"), which returns Recipe: Pasta. The supplied value only affects that call.
The default fills the slot only because the call left prefix out.

Everyday analogy: a coffee order. A customer who says only "latte" gets the shop's usual size. Saying "large" changes the size for that order only. The shop and its sizes are invented here.

✎ Try it yourselfKnowledge check · Practice only

Practice: Read the default.

def make_title(topic, prefix="Chat"): return prefix + ": " + topic print(make_title("Pasta", "Recipe")) What does the program print?

return hands a value back.

return sends a value out of the function to the code that called it. It also ends the function at that line. The caller can store the value in a variable.

def make_title(topic, prefix="Chat"):
    return prefix + ": " + topic

x = make_title("Soup")
print(x)   # Chat: Soup
Diagram showing make_title("Soup") returning "Chat: Soup" into x, while make_note("Milk") has no return statement and therefore gives x the value None.
return sends the value out to the caller, and ends that call.

A function with no return line gives back None. That is Python's value for no result. The body still runs when the function is called.

def make_note(text):
    note = "Note: " + text

x = make_note("Milk")
print(x)   # None

The text built inside make_note is not handed back, so x holds None.

✎ Try it yourselfKnowledge check · Practice only

Practice: print or return?

def show_title(topic): print("Title: " + topic) x = show_title("Pasta") print(x) What is printed, in order?

A docstring says what the function does.

A docstring is a string used as the first statement in the function body, under the def line. Python keeps it with the function, and help() shows it.

A common layout has three parts: a one-line summary, an Args: list, and a Returns: line. This is one common style, not the only one.

def make_title(topic, prefix="Chat"):
    """Build a title from a prefix and a topic.

    Args:
        topic: The subject, such as "Pasta".
        prefix: The word before the colon.
            Defaults to "Chat".

    Returns:
        The title as one string,
        such as "Chat: Pasta".
    """
    return prefix + ": " + topic

help(make_title)

Reading the docstring, part by part:

  • Summary: the first line says what the function does. Keep it to one line.
  • Args: one entry for each parameter, with its meaning. A default value goes here too.
  • Returns: the value the caller receives. It does not describe text shown on screen.

Calling help(make_title) prints the signature, make_title(topic, prefix='Chat'), and then the docstring with its indentation removed.

Quick questions

Does a docstring change what the function returns?
No. It is a string that describes the function. The return line decides the result.
Does a Returns entry describe what gets printed?
No. It describes the value handed back to the caller. Text on screen comes from print.
Is a docstring required?
No. Python runs the function without one. It helps readers, and it is worth writing for functions other people will use. Keep it in step with the code, because help() shows it as is.

Try the title builder.

The toy code holds the two functions from this lesson. Each button sets one call. The lab shows the text that is printed on screen and the value handed back to the caller as two separate results. Both def lines always run, because they store the functions.

Try it in this order:

  1. Press make_title("Pasta"). Read the handed back value, then the shown value.
  2. Press make_title("Pasta", "Recipe"). Note which prefix changed.
  3. Press show_title("Pasta"). Look for the text under Shown on screen, and None under Handed back.
  4. Press print(make_title("Pasta")). The same text now appears on screen.

Toy sandbox: a made-up Python snippet with the two functions from this lesson, not a live interpreter. Highlighted lines ran. Dimmed body lines were skipped. The def lines always run to store the functions.

def make_title(topic, prefix="Chat"):    return prefix + ": " + topic def show_title(topic):    print("Title: " + topic) make_title("Pasta")
Shown on screenNothing
Handed back to the caller"Chat: Pasta"
The prefix was left out, so the default Chat is used. The value is handed back, but nothing is shown.
✎ Try it yourselfKnowledge check · Practice only

Check your understanding.

def add_note(text): return "Note: " + text add_note("Milk") print("done") This is a script file, run from top to bottom. What does the program print?
THE TAKEAWAY

Take this with you.

  • def stores, a call runs: writing a def line does not run the body.
  • Arguments and defaults: an argument fills a parameter. A default fills in when the call leaves it out.
  • return or print: return hands a value back to the caller. print only shows text.
  • Docstring: a string at the start of the body with a summary, Args and Returns. help() shows it.
Back to Chapter P1 →