Chapter 8
Writing Your Own Functions
Turn a Task into a Function
At the end of Chapter 7, you built a menu that could add,
while True:
command = input("Command: ").strip().lower()
if command == "add":
# ask for an item, store it, and confirm it
...
elif command == "list":
# handle an empty list or print every numbered item
...
elif command == "count":
# report the number of items
...
To understand the list command, a reader has to find that branch and read all the lines inside it. The loop is doing two jobs at once: choosing an action and explaining how every action works.
You already know what could improve that.
if command == "add":
add_item(items)
elif command == "list":
show_items(items)
elif command == "count":
show_count(items)
Even before you know how those three
That is the main reason to write a function: it gives one understandable operation a name.
You already use functions
Chapter 3 introduced function calls:
name = input("What is your name? ")
letter_count = len(name)
print(letter_count)
input, len, and print are functions. You know three important parts of their behavior:
A call uses parentheses, as in
len(name).A call can receive an
, such as name.A call can produce a
, such as the number from len(name).
Until now, someone else wrote every function you called. This chapter gives you the other half of the picture: defining your own.
Definition first, call second
A function definition starts with def. It describes what should happen when the function is called:
The definition has two parts:
def show_count(items):
This first line gives the function its name and says what information it expects.
print(f"Items stored: {len(items)}")
The indented body contains the work.
Defining the function does not perform that work. Python remembers the definition. The work happens later, at the call:
show_count(books)
That separation is useful. Define an operation once, then call it wherever the program needs it.
A name creates a useful level of detail
Imagine reading directions that say:
Move your right foot, shift your weight, move your left foot, shift your weight, and keep repeating.
Most people would simply say:
Walk to the door.
The shorter instruction is useful because the word walk names a familiar operation. A good function name does the same thing for code. It lets one part of a program state the plan while the function body holds the details.
Functions do not automatically improve a program. A vague name such as do_thing() hides information. A focused name such as show_items() reveals intent.
In this chapter, you will learn to write the details and choose the names.
What does this program print?
def announce():
print("The gate is open.")
print("Ready.")
Which function name gives the clearest summary of its job?