Writing Your Own Functions · practice
Let Functions Work Together
A
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:
The program calls
make_heading.make_headingcallsclean_title.clean_titlereturns"READING LIST"tomake_heading.make_headingbuilds and returns"=== READING LIST ==="to the program.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
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
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 "=== 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
clean_name(text)returns the text with surrounding spaces removed and all letters uppercase.make_heading(text)callsclean_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