Functions: The Foundation of Structured Programming
Functions provide an effective way to package and reuse program
code, as already explained in More Python: Reusing Code. For
example, suppose we find that we often want to read text from an HTML
file. This involves several steps: opening the file, reading it in,
normalizing whitespace, and stripping HTML markup. We can collect these
steps into a function, and give it a name such as get_text(), as shown in Example 4-1.
Example 4-1. Read text from a file.
import re
def get_text(file):
"""Read text from a file, normalizing whitespace and stripping HTML markup."""
text = open(file).read()
text = re.sub('\s+', ' ', text)
text = re.sub(r'<.*?>', ' ', text)
return textNow, any time we want to get cleaned-up text from an HTML file, we
can just call get_text() with the
name of the file as its only argument. It will return a string, and we
can assign this to a variable, e.g., contents =
get_text("test.html"). Each time we want to use this series of
steps, we only have to call the function.
Using functions has the benefit of saving space in our program.
More importantly, our choice of name for the function helps make the
program readable. In the case of the preceding
example, whenever our program needs to read cleaned-up text from a file
we don’t have to clutter the program with four lines of code; we simply
need to call get_text(). This naming helps to provide some “semantic interpretation”—it helps a reader of our program to see what the program ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access