0%

Writing Your Own Functions · practice

Let Functions Work Together

A can call another function. This lets you build a larger operation from smaller named pieces.

Suppose a menu title should have its surrounding spaces removed and its letters capitalized:

def clean_title(text):
    return text.strip().upper()

A second function can use that result:

def make_heading(text):
    clean = clean_title(text)
    return f"=== {clean} ==="

Then the program starts the whole chain with one call:

heading = make_heading("  reading list  ")
print(heading)

The calls happen in this order:

  1. The program calls make_heading.

  2. make_heading calls clean_title.

  3. clean_title returns "READING LIST" to make_heading.

  4. make_heading builds and returns "=== READING LIST ===" to the program.

  5. The program stores and prints the result.

Each function has one focused job. clean_title knows how to clean text. make_heading knows how to decorate the cleaned result.

Why not put everything in one function?

This version is shorter:

def make_heading(text):
    return f"=== {text.strip().upper()} ==="

For one small , that may be perfectly clear. Separate functions become valuable when:

  • an operation has a useful name;

  • the operation is needed in more than one place;

  • each part deserves to be checked on its own;

  • splitting the work makes a larger function easier to read.

Do not split every line into a function. Create boundaries that help a reader understand the program.

Returned values connect functions

Notice that clean_title returns text. It does not print it. make_heading needs that text to build another , so a is the right connection.

If clean_title only printed, these lines inside make_heading would build the wrong heading:

clean = clean_title(text)
return f"=== {clean} ==="

clean would hold None, so the returned would be "=== None ===". The code would run, but it would not return the cleaned name.

The ideas from the last three lessons fit together:

  • bring information into a function;

  • hold its temporary work;

  • return values carry useful results back to the caller;

  • another function can become that caller.

Which function receives the value "map" directly from clean_word?

def clean_word(text):
    return text.strip().lower()

def make_label(text):
    word = clean_word(text)
    return f"[{word}]"

label = make_label(" Map ")

Task

Complete two that work together:

  1. clean_name(text) returns the text with surrounding spaces removed and all letters uppercase.

  2. make_heading(text) calls clean_name(text) and returns the cleaned name between === and ===.

Keep the existing call and print statement.

Expected output:

=== READING LIST ===

After it passes, use Step in the exercise editor. Follow execution from the top-level call into make_heading, then into clean_name, and back out through both .